我是套接字编程的新手。每次运行客户端程序时都会说“#34;无法连接到服务器"”。任何人都可以告诉我我在哪里犯了错误。 任何帮助将不胜感激。
这是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;
}
答案 0 :(得分: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
。