如何解决C Socket 代码可以在 LAN 内工作,但不能在 WAN 上工作吗?连接被拒绝?
我一直在开发一个连接 4 游戏,它在我的主要功能中包含客户端和服务器代码,用于 TCP 连接。我无法通过互联网连接。我尝试在不在我的 LAN 上的笔记本电脑上运行我的客户端代码,指定我的 LAN 的公共 IP 和所需的端口号。但是,当连接失败时,继续拒绝连接作为我的错误消息。
//客户端代码
if(argc == 3){
turn = CLIENT;
int status,client_sockfd;
struct addrinfo hints,*res;
memset(&hints,sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if((status = getaddrinfo(argv[1],argv[2],&hints,&res)) != 0){
fprintf(stderr,"getaddrinfo error: %s\n",gai_strerror(status));
exit(1);
}
if((client_sockfd = socket(res -> ai_family,res -> ai_socktype,res -> ai_protocol)) == -1){
fprintf(stderr,"socket creation error: %s\n",gai_strerror(client_sockfd));
exit(1);
}
if((connect(client_sockfd,res -> ai_addr,res -> ai_addrlen)) == -1){
perror("cannot connect");
exit(1);
}
freeaddrinfo(res); //free res structure
//Start of Game: Client
recv(client_sockfd,player1,25,0);
printf("Player 2,enter your name:\n");
fgets(player2,sizeof(player2),stdin);
send(client_sockfd,player2,0);
sock = client_sockfd;
}
//服务器网络代码
else{
turn = SERVER;
int server_sockfd;
printf("Setting up the game\n");
//server port
if(argc == 2)
myport = argv[1];
else
myport = "12345";
int status,sock_fd;
int opt = 1;
struct addrinfo hints,*res;
struct sockaddr_storage their_addr;
socklen_t addr_size;
memset(&hints,sizeof(hints)); //make sure hints is empty
hints.ai_family = AF_UNSPEC; //ipv6 or ipv4 doesn't matter
hints.ai_socktype = SOCK_STREAM; //require TCP stream sockets
hints.ai_flags = AI_PASSIVE;
//load res adderinfo struct
if((status = getaddrinfo(NULL,myport,gai_strerror(status));
exit(1);
}
//create socket with res
if((sock_fd = socket(res -> ai_family,gai_strerror(sock_fd));
exit(1);
}
//reuseable socket
if(setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)) == -1){
perror("setsockopt");
exit(1);
}
//bind socket for use
if((bind(sock_fd,res-> ai_addrlen)) == -1){
perror("binding fail");
exit(1);
}
//listen with a backlog of 5
listen(sock_fd,5);
addr_size = sizeof(their_addr);
if((server_sockfd = accept(sock_fd,(struct sockaddr *)&their_addr,&addr_size)) == -1){
perror("accepting failure");
exit(1);
}
freeaddrinfo(res); //free res structure
//Start of Game: Server
printf("Player 1,please enter your name:\n");
fgets(player1,sizeof(player1),stdin);
send(server_sockfd,0);
recv(server_sockfd,0);
sock = server_sockfd;
}
有什么想法吗?根据我的理解,作为客户端,我的数据包应该到达服务器的网关,而 NAT 应该使用我的目标端口将我的消息重定向到服务器?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。