gpt4 book ai didi

编写客户端程序时出现编译错误

转载 作者:行者123 更新时间:2023-11-30 15:27:20 25 4
gpt4 key购买 nike

我是套接字编程的新手。我查看了教程点中的一个程序。我对该程序做了一些更改,但在编译时遇到了错误。我我附上一张图片来说明错误。 enter image description here .

另外,我不明白sin_family和sin_port是什么,要不要分别替换成serv_addr_family和serv_addr_port呢?

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#define portno 5432

int main(int argc, char *argv[])
{
int sockfd,n;
const struct sockaddr_in serv_addr;
const struct hostent *server;

char buffer[256];

if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
return;
}

server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
return;
}

/* Create a socket point */
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy(*server->h_addr,
(char *)&serv_addr.sin_addr,
server->h_length);
serv_addr.sin_port = htons(portno);

sockfd = socket(PF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
return;
}
/* Now connect to the server */
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
{
perror("ERROR connecting");
return;
}
/* Now ask for a message from the user, this message
* will be read by server
*/
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
/* Send message to the server */
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
{
perror("ERROR writing to socket");
return;
}
/* Now read server response */
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
{
perror("ERROR reading from socket");
return;
}
printf("%s\n",buffer);
return 0;
}

最佳答案

你必须在结构之前删除const。它用于配置您的套接字。(端口,IP,...)

int sockfd,n;
const struct sockaddr_in serv_addr;
const struct hostent *server;

int sockfd,n;
struct sockaddr_in serv_addr;
struct hostent *server;

关于编写客户端程序时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27059727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com