我不明白为什么我无法通过我的公共 IP 建立连接。使用本地 IP 时可以连接。
我有适当的防火墙端口例外,并且我的路由器 NAT 具有到我的机器的端口转发配置。
这是一个相当基本的程序,可以通过我的本地 IP 连接,但在使用公共 IP 时会出现“连接被拒绝”的情况。
有什么帮助吗?(我还设置了一个 nginx 服务器,它无法从公共 IP 访问,但可以通过本地 IP 访问)
客户:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
sockaddr_in address;
int res;
int sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (-1 == sfd)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(6511);
res = inet_pton(AF_INET, "201.93.179.98", &address.sin_addr); /* connect through public IP doesn't work */
//res = inet_pton(AF_INET, "192.168.1.71", &address.sin_addr);
if (0 > res)
{
perror("error: first parameter is not a valid address family");
close(sfd);
exit(EXIT_FAILURE);
}
else if (0 == res)
{
perror("char string (second parameter does not contain valid ipaddress)");
close(sfd);
exit(EXIT_FAILURE);
}
if (-1 == connect(sfd, (sockaddr *)&address, sizeof(address)))
{
perror("connect failed");
close(sfd);
exit(EXIT_FAILURE);
}
/* perform read write operations ... */
char msg[] = "Hello World";
write(sfd, (void *)msg, sizeof(msg));
printf("sent %s\n", msg);
shutdown(sfd, SHUT_RDWR);
close(sfd);
return EXIT_SUCCESS;
}
服务器:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
sockaddr_in address;
int sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if(-1 == sfd)
{
perror("can not create socket");
exit(EXIT_FAILURE);
}
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(6511);
address.sin_addr.s_addr = inet_addr("192.168.1.71"); /* serve on given interface */
if(-1 == bind(sfd, (sockaddr *)&address, sizeof(address)))
{
perror("error bind failed");
close(sfd);
exit(EXIT_FAILURE);
}
if(-1 == listen(sfd, 10))
{
perror("error listen failed");
close(sfd);
exit(EXIT_FAILURE);
}
for(;;)
{
int cfd = accept(sfd, NULL, NULL);
if(0 > cfd)
{
perror("error accept failed");
close(sfd);
exit(EXIT_FAILURE);
}
/* perform read write operations ...
read(cfd,buff,size)*/
char msg[100] = {};
read(cfd, (void *)msg, sizeof(msg));
printf("got %s\n", msg);
if (-1 == shutdown(cfd, SHUT_RDWR))
{
perror("can not shutdown socket");
close(cfd);
close(sfd);
exit(EXIT_FAILURE);
}
close(cfd);
}
close(sfd);
return EXIT_SUCCESS;
}
答案1
您需要配置路由器/防火墙以允许 NAT 发夹。如果您有 SOHO 路由器,它可能不支持此功能。如果您有 Cisco ASA 之类的路由器,则应该阅读文档。