BartekMaciąg
BartekMaciąg

Reputation: 11

Error with bind() and listen() functions (WinSock)

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 "109.95.202.122" but it isn't working.

I have fail : Fail bind() and Listen Error

#pragma comment(lib, "Ws2_32.lib")

#include <sdkddkver.h>
#include <conio.h>
#include <stdio.h>

#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string>
#include <process.h>
#define MY_IP       "109.95.202.122"
using namespace std;
int main()
{
    WSADATA wsaData;

    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() );
        WSACleanup();
        return 1;
    }
    sockaddr_in service;
    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;     
        for(;;)
        {
            char chWiadomosc[1000];
            recv(mainSocket, chWiadomosc, sizeof(chWiadomosc), NULL);

        }
    }
}

Upvotes: 1

Views: 3255

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595349

if either bind() or 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 109.95.202.122, 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 109.95.202.122 is a local IP of the server then all is well. However, if 109.95.202.122 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.

Upvotes: 1

Related Questions