gpt4 book ai didi

连接服务器-客户端

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

我是套接字编程的新手。每次我运行客户端程序时,它都会说“无法连接到服务器”。谁能告诉我我在哪里犯了错误。任何帮助将不胜感激。

这是client.c

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
int host_socket=0;
struct sockaddr_in host_addr,serv_addr;
char sendbuffer[1024];
char recvbuffer[1024];

host_socket = socket(AF_INET,SOCK_STREAM,0);
host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(5000);
host_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

if(connect(host_socket,(struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
printf("could not connect to server !!");
return -1;
}
strcpy(sendbuffer,"127.0.0.1");

send(host_socket,sendbuffer,strlen(sendbuffer),0);

recv(host_socket,recvbuffer,sizeof(recvbuffer),0);
fputs(recvbuffer,stdout);

return 0;
}

这是 server.c

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
int serv_socket=0;
struct sockaddr_in serv_addr,host_addr;
char recvbuffer[1024];
char sendbuffer[1024];
socklen_t add_len;

serv_socket = socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);


bind(serv_socket,(struct sockaddr*)&serv_addr,sizeof(serv_addr));

if(listen(serv_socket,10)<0)
{printf("no listening");}

add_len = sizeof(host_addr);
accept(serv_socket,(struct sockaddr*)&host_addr,&add_len);
recv(serv_socket,recvbuffer,sizeof(recvbuffer),0);
strcpy(sendbuffer,recvbuffer);
send(serv_socket,sendbuffer,sizeof(sendbuffer),0);

return 0;
}

最佳答案

host_addr.sin_family = AF_INET;
host_addr.sin_port = htons(5000);
host_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

if(connect(host_socket,(struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
{
printf("could not connect to server !!");
return -1;
}

您将服务器参数放入 host_addr 中,但您的 connect 调用使用未初始化的 serv_addr

关于连接服务器-客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23067304/

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