Search code examples
c++linuxsocketstcpip-address

Bind with 127.0.0.1 and INADDR_ANY


I am learning socket programming,when I try to create a connection between my client and server, Only when I set as follows
client.cpp:

    serAdd.sin_addr.s_addr=htol(INADDR_ANY);  

server.cpp:

    serAdd.sin_addr.s_addr=htol(INADDR_ANY);
    bind(server,(const sockaddr *)&serAdd,sizeof(serAdd);  

The connection can be estalished successfully.If I changed INADDR_ANY to 127.0.0.1,the connection can not be established.The below is my program:

client.cpp:

#define portNum 6666
int main()
{
    int client,i;
    sockaddr_in serAdd;
    char *ip="127.0.0.1";


    client=socket(AF_INET,SOCK_STREAM,0);
    if(client<0)
    {
        cout<<"Fail to create socket..."<<endl;
        return 0;
    }

    cout<<"Creating connection..."<<endl;

    serAdd.sin_family=AF_INET;
    serAdd.sin_addr.s_addr=htonl(*ip);
    serAdd.sin_port=htons(portNum);

    if(connect(client,(const sockaddr *)&serAdd,sizeof(serAdd))==0)
    {
        cout<<"Connected!"<<endl;
        cin>>i;
    }
    else 
    {
        cout<<"Connect failed..."<<endl;
        cin>>i;
    }
}  

server.cpp:

#define portNum 6666
int main()
{
    int client,server;
    sockaddr_in serAdd,
            cliAdd;
    char *ip="127.0.0.1";

    server=socket(AF_INET,SOCK_STREAM,0);
    if(server<0)
    {
        cout<<"Fail to create socket..."<<endl;
        return 0;
    }

    cout<<"Binding..."<<endl;

    serAdd.sin_family=AF_INET;
    serAdd.sin_addr.s_addr=htonl(INADDR_ANY);
    serAdd.sin_port=htons(portNum);

    if(bind(server,(const sockaddr *)&serAdd,sizeof(serAdd))==0)
    {
        cout<<"Binding succed!..."<<endl;
    }
    else
    {
        cout<<"Binding failed..."<<endl;
        return 0;
    }

if(listen(server,1)==0)
{
    cout<<"Listening..."<<endl;
}
else
{
    cout<<"Listening failed..."<<endl;
    return 0;
}

socklen_t size=sizeof(cliAdd);
while(1)
    {
        if(accept(server,(sockaddr *)&cliAdd,&size)>=0)
            cout<<"Connection created!"<<endl;
        else
        {
            cout<<"accept failed..."<<endl;
            return 0;
        }
    }
}

Solution

  • Use inet_addr() to set the IPv4 address from a "string":

    serAdd.sin_addr.s_addr = inet_addr("127.0.0.1");
    

    or

    inet_aton("127.0.0.1", &serAdd.sin_addr);
    

    To support IPv6 or possible other upcoming address schema you want to really use inet_pton().

    In your IPv4 case this might look like this:

    inet_pton(AF_INET, "127.0.0.1", &serAdd.sin_addr);
    

    If I changed INADDR_ANY to 127.0.0.1

    Doing something like this

    ... = htol("127.0.0.1");
    

    should have made the compiler yell out a warning. Take warnings serious.


    As noted by Chris Dodd in this special case of assigning the loop-back address (127.0.0.1) you could short-cut this by doing

    serAdd.sin_addr.s_addr = INADDR_LOOPBACK;