我用C 编写了一个简单的套接字编程应用程序。这段代码正在处理环回地址。如果两台计算机(一台服务器一个客户端)在同一个网络中(我在大学 LAN 网络上尝试过),这个程序也可以很好地工作但是当我尝试在两台完全不同的计算机上运行相同的代码时(在两个不同的网络中)然后它在客户端的“连接”方法中显示错误。客户端无法连接到服务器。请帮帮我。我几乎尝试了所有方法,但没有任何帮助,所以请帮助我。请尽快帮助我现在一个月。先谢谢了!
这是代码:对于Client.c
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
int chat();
int main(){
chat();
}
int chat()
{
int clientid, n = 0;
char msgsend[512], msgrecv[512];
struct sockaddr_in client;
memset(msgrecv, '0', sizeof(msgrecv));
clientid = socket(AF_INET, SOCK_STREAM, 0);
if(clientid == -1){
printf("Could not create a socket!\n");
return -1;
}
client.sin_family = AF_INET;
client.sin_addr.s_addr = /*INADDR_ANY;*/inet_addr("10.200.56.187");
client.sin_port = htons(5001);
printf(" Trying to connect...");
if(connect(clientid, (struct sockaddr*)&client, sizeof(client)) < 0){
printf("Error:Connection failed\n");
return -1;
}
printf("Connected");
while(1){
printf("please enter your reply\n");
gets(msgsend);
send(clientid, msgsend, sizeof(msgsend) - 1, 0);
n = recv(clientid, msgrecv, sizeof(msgrecv) - 1, 0);
if(n < 0){
printf("Read error\n");
}
printf("\n");
printf("server says:");
msgrecv[n] = 0;
fputs(msgrecv, stdout);
printf("\n");
}
return 0;
}
And here is the code:
for server.c
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include<fcntl.h>
int chat();
int main(){
chat();
}
int chat(){
int serverid, clientid, n = 0, len;
char msgsend[512], msgrecv[512];
struct sockaddr_in server,client;
serverid = socket(AF_INET, SOCK_STREAM, 0);
memset(&server, '0', sizeof(server));
memset(msgrecv, '0', sizeof(msgrecv));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(5001);
bind(serverid, (struct sockaddr*)&server, sizeof(server));
if( listen(serverid, 10) == -1){
printf("ERROR");
return -1;
}
len = sizeof(client);
clientid = accept(serverid, (struct sockaddr*)&client, &len);
while(1){
n = recv(clientid, msgrecv, sizeof(msgrecv) - 1, 0);
if(n < 0){
printf("Error while reading...\n");
return -1;
}
printf("client says:");
msgrecv[n] = 0;
fputs(msgrecv, stdout);
printf("\n");
printf("enter your reply\n");
gets(msgsend);
send(clientid, msgsend, sizeof(msgsend) - 1, 0);
printf("\n");
}
return 0;
}