我对套接字有点陌生。所以我设置了一个服务器,我想通过互联网将客户端连接到它。我不明白我做错了什么,因为以下示例适用于环回地址 (127.0.0.1),但当其他人尝试使用我的外部 IP 地址连接到我的服务器时则不起作用。是不是没那么简单,还是我的代码做错了什么?
编辑:(当客户端到达connect()
时,会特别卡住,给出connect:连接超时
错误)
Edit2:我尝试在服务器代码中使用我的广播地址 inet_addr("192.168.1.255")
而不是 INADDR_ANY
。没有变化。
这是我的服务器代码:
#include <stdio.h>
#include <stdlib.h\
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void) {
int temp;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
int numbytes;
char buf[100];
int sock_fd; // server file descriptor
int new_fd; // client file descriptor
sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock_fd == -1) { perror("socket"); exit(1); }
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9000);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
temp = bind(sock_fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr));
if (temp == -1) { perror("bind"); exit(1); }
temp = listen(sock_fd, 5);
if (temp == -1) { perror("listen"); exit(1); }
printf("\nListening for new connections on port %d ...\n\n", 9000);
while (1) {
sin_size = sizeof(struct sockaddr_in);
new_fd = accept(sock_fd, (struct sockaddr*)&their_addr, &sin_size);
if (new_fd == -1) { perror("accept"); continue; }
printf("Got connection from IP (%s)\n", inet_ntoa(their_addr.sin_addr));
close(new_fd);
}
}
这是我的客户端代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(int argc, char *argv[]) {
int temp;
struct hostent *host_info;
struct sockaddr_in serv_addr;
char ip_addr[100];
int numbytes;
char buf[100];
int sock_fd;
inet_pton(AF_INET, argv[5], &serv_addr.sin_addr);
host_info = gethostbyaddr(&serv_addr.sin_addr, sizeof serv_addr.sin_addr, AF_INET);
if (host_info == NULL) { herror("gethostbyname"); exit(1); }
printf("\nServer: '%s' (IP: %s , Port: %d)\n\n", argv[1], inet_ntop(AF_INET, host_info->h_addr, ip_addr, 100), 9000);
sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock_fd == -1) { perror("socket"); exit(1); }
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(9000);
serv_addr.sin_addr = *((struct in_addr *)host_info->h_addr);
bzero(&(serv_addr.sin_zero), 8);
temp = connect(sock_fd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr));
if (temp == -1) { perror("connect"); exit(1); }
close(sock_fd);
exit(0);
}
最佳答案
在这里发布答案,以便我可以接受我的整体解决方案。问题是我没有按照 @AdamRosenfield 指示转发路由器上的端口,然后在我这样做之后,我将服务器地址更改为:
my_addr.sin_addr.s_addr = inet_addr("192.168.1.2");
根据ifconfig
这是我的本地IP地址(我使用的是Ubuntu)。
现在我唯一的问题是,除了我之外,其他任何人都可以从我自己的电脑连接到我的服务器,但这可能是我的路由器特有的问题,根据@nos。
如果有人知道如何解决这个问题,请更新我(我尝试使用环回地址、我的外部 IP、我的本地 IP 等连接客户端,但没有任何效果)。
关于c - 如何仅使用服务器的 IP 连接到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27884988/