Fan*_*ier 4 c connection client-server
大家好,我要扯头发了。我有一个尝试连接到服务器的客户端,使用gethostbyname(), socket(), bind(),一切似乎都很好,但是当尝试它时,connect()它只是挂在那里,服务器看不到来自客户端的任何内容。我知道服务器可以正常工作,因为另一个客户端(也在 C 语言中)可以正常连接。是什么导致服务器看不到此传入连接?我已经无计可施了。这两个不同的客户也非常相似,所以我更加迷失了。
if (argc == 2) {
host = argv[1]; // server address
}
else {
printf("plz read the manual\n");
exit(1);
}
hserver = gethostbyname(host);
if (hserver) {
printf("host found: %p\n", hserver);
printf("host found: %s\n", hserver->h_name );
}
else {
printf("host not found\n");
exit(1);
}
bzero((char * ) &server_address, sizeof(server_address)); // copy zeroes into string
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(hserver->h_addr);
server_address.sin_port = htons(SERVER_PORT);
bzero((char * ) &client_address, sizeof(client_address)); // copy zeroes into string
client_address.sin_family = AF_INET;
client_address.sin_addr.s_addr = htonl(INADDR_ANY);
client_address.sin_port = htons(SERVER_PORT);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
exit(1);
else {
printf("socket is opened: %i \n", sockfd);
info.sock_fd = sockfd;
rv = fcntl(sockfd, F_SETFL, O_NONBLOCK); // socket set to NONBLOCK
if(rv < 0)
printf("nonblock failed: %i %s\n", errno, strerror(errno));
else
printf("socket is set nonblock\n");
}
timeout.tv_sec = 0; // seconds
timeout.tv_usec = 500000; // micro seconds ( 0.5 seconds)
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval));
rv = bind(sockfd, (struct sockaddr *) &client_address, sizeof(client_address));
if (rv < 0) {
printf("MAIN: ERROR bind() %i: %s\n", errno, strerror(errno));
exit(1);
}
else
printf("socket is bound\n");
rv = connect(sockfd, (struct sockaddr *) &server_address, sizeof(server_address));
printf("rv = %i\n", rv);
if (rv < 0) {
printf("MAIN: ERROR connect() %i: %s\n", errno, strerror(errno));
exit(1);
}
else
printf("connected\n");
Run Code Online (Sandbox Code Playgroud)
任何想法或见解都将受到极大的赞赏。
-傅里叶
编辑:如果套接字未设置为非阻塞,则它会挂起。如果套接字设置为非阻塞,那么我得到ERROR connect() 115: Operation now in progress
[EINPROGRESS] 套接字的文件描述符设置了 O_NONBLOCK,无法立即建立连接;连接应异步建立。
我还想提一下,服务器和客户端运行在彼此相邻的计算机上,通过一个路由器连接。
该gethostbyname()函数以网络字节顺序生成地址,因此您不需要将它们传递给htonl(). 此外,该hostent->h_addr条目是指向该地址的指针。替换这一行:
server_address.sin_addr.s_addr = htonl(hserver->h_addr);
Run Code Online (Sandbox Code Playgroud)
和:
memcpy(&server_address.sin_addr, hserver->h_addr, hserver->h_length);
Run Code Online (Sandbox Code Playgroud)