I couldn't figure out why I can't make a connection through my public IP. When using a local IP it works.
I have the proper firewall port exceptions, and my router NAT has the configurations for port forwarding to my machine.
This is a fairly basic program that is able to connect through my local IP, but gets "connection refused" when using the public one.
Any help? (I've also setup a nginx server which can't be accessed from public IP, but works through local one)
Client:
#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;
}
Server:
#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;
}