I'm working with
WinSock and I have one problem: if I define
MY_IP to be "127.0.0.1" this works but I don't want this I want to define
MY_IP to be "18.104.22.168" but it isn't working.
I have fail :
Fail bind() and
#pragma comment(lib, "Ws2_32.lib")
#define MY_IP "22.214.171.124"
using namespace std;
int result = WSAStartup( MAKEWORD( 2, 2 ), & wsaData );
if( result != NO_ERROR )
cout << "Initialization error." << endl;
SOCKET mainSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if( mainSocket == INVALID_SOCKET )
printf( "Error creating socket: %ld\n", WSAGetLastError() );
memset( & service, 0, sizeof( service ) );
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(MY_IP);
service.sin_port = htons( 27015 );
if(bind(mainSocket, (SOCKADDR*)&service, sizeof(service))== SOCKET_ERROR)
cout << "Fail bind()" << endl;
closesocket( mainSocket );
if(listen(mainSocket, 1) == SOCKET_ERROR)
cout << "Listen Error";
cout << "Oczekiwanie na polaczenie" << endl;
SOCKET acceptSocket = SOCKET_ERROR;
while( acceptSocket == SOCKET_ERROR )
acceptSocket = accept( mainSocket, NULL, NULL);
if( acceptSocket != SOCKET_ERROR)
cout << "Connected ! :D" << endl;
recv(mainSocket, chWiadomosc, sizeof(chWiadomosc), NULL);
listen() fails, call
WSAGetLastError() to find out why it failed.
If a server binds itself to 127.0.0.1, clients will only be able to connect to 127.0.0.1. If clients need to connect to 126.96.36.199, the server needs to bind to the local IP that will be accepting the clients, or specify
INADDR_ANY to bind to all available local IPs. If 188.8.131.52 is a local IP of the server then all is well. However, if 184.108.40.206 is actually the public IP of a router/NAT that the server is running behind, the server needs to bind to the local IP that the router/NAT is configured to port-forward inbounds requests to.
bind() can only bind to local IPs that belong to the machine that
bind() is running on.