我正在学习sockets,我正在学习课本中的一些示例代码。我有两台电脑,一台是服务器,另一台是客户机。我试图让两台pc通过套接字进行通信,但是client connect()调用挂起。因为我刚开始学习,所以我不知道发生了什么。
我试图搜索c connect()挂起,但没有成功。我通过ifcongifinet 138.51.83.123
了解我的服务器IP
服务器:
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include <sys/types.h>
#include <signal.h>
#define SIZE sizeof(struct sockaddr_in)
void catcher(int sig);
int newsockfd;
int main(){
int sockfd;
char c;
struct sockaddr_in server = {AF_INET, 7000, INADDR_ANY};
static struct sigaction act;
act.sa_handler = catcher;
sigfillset(&(act.sa_mask));
sigaction(SIGPIPE, &act, NULL);
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket call failed");
exit(1);
}
if(bind(sockfd, (struct sockaddr*)&server, SIZE) == -1){
perror("bind call failed");
exit(1);
}
if(listen(sockfd, 5) == -1){
perror("listen call failed");
exit(1);
}
for(;;){
if((newsockfd = accept(sockfd, NULL, NULL)) == -1){
perror("accept call failed");
continue;
}
if(fork() == 0){
// keep reading if not EOF
while(recv(newsockfd, &c, 1, 0) > 0){
printf("***received: %c\n", c);
c = toupper(c);
send(newsockfd, &c, 1, 0);
}
close(newsockfd);
exit(0);
}
// parent no need for newsockfd
close(newsockfd);
}
return 0;
}
void catcher(int sig){
close(newsockfd);
exit(0);
}
客户:
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#define SIZE sizeof(struct sockaddr_in)
int main(){
int sockfd;
char c, rc;
struct sockaddr_in server = {AF_INET, 7000};
server.sin_addr.s_addr = inet_addr("138.51.83.71");
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket call failed");
exit(1);
}
if(connect(sockfd, (struct sockaddr*)&server, SIZE) == -1){
printf("here\n");
perror("connect call failed");
exit(1);
}
printf("here\n"); // never got printed out
for(;;){
printf("Input a lowercase char\n");
c = getchar();
send(sockfd, &c, 1, 0);
if(recv(sockfd, &rc, 1, 0) > 0) printf("receive: %c", rc);
else{
printf("server died\n");
close(sockfd);
exit(1);
}
}
}
在客户机中,
printf("here\n"); // never got printed out
所以我猜客户机会挂起(我试着把这个printf放在connect()
之前,然后打印出来)。有人能帮忙吗?因为我之前没有网络编程的知识,所以我甚至不知道如何调试。 最佳答案
首先尝试从客户端计算机ping服务器的IP地址并查看结果。如果ping不成功,则表示网络连接有问题。我用服务器的IP作为127.0.0.1(本地主机)运行了您的程序,它运行得很好,这表明您的代码没有问题。