[Solved] Winsock programming connecting to a public ip


The issue is with your server. You are binding it to 127.0.0.1. This means your server will only bind to the loopback interface, so only clients running on the same machine as the server will be able to connect to the server using this same interface.

If you want your server to accept clients from a public network interface, you have to bind to that interface’s IP instead:

server.sin_addr.s_addr = inet_addr("<IP belonging to the public interface>");

Or, you can bind your server to all available network interfaces:

server.sin_addr.s_addr = inet_addr("0.0.0.0");

Or:

server.sin_addr.s_addr = INADDR_ANY;

Note that you can only bind to IP(s) that belong to the machine that the server is running on. If the public IP the client is trying to connect to belongs to a NAT/router, you must bind the server to its local LAN IP that is connected to the NAT/router, and then set up port forwarding on the NAT/router to forward packets from an open port on the NAT/router’s public IP to the listening port on the server’s LAN IP. If the NAT/router supports uPNP, your server can setup the port forwarding programmably. Otherwise, the NAT/router’s admin has to setup the forwarding manually.

4

solved Winsock programming connecting to a public ip