简体   繁体   中英

What IP address should be bound to a server application's socket?

I've just recently started playing around with sockets in C. Today I've been trying to write a server application to run on an old laptop of mine, just to experiment a bit. I'd like for the server's services to be accessible from remote hosts and I'm confused about which IP address the server's socket should be bound to: is there an IP address that uniquely identifies my machine online or am I missing a step (or possibly many more) here?

struct sockaddr_in serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));

serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddress.sin_port = htons(8080);

if(bind(serverSocketDescriptor, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) {

    printf("bind() failed\n");
    closesocket(serverSocketDescriptor);
    WSACleanup();
    return EXIT_FAILURE;
}

You want to bind to INADDR_ANY , which translates to 0.0.0.0.

serverAddress.sin_addr.s_addr = INADDR_ANY;

Binding to this address means the socket is bound to all local addresses, including localhost and any external IPs the host may have.

Suggest reading: server code sequence

//  int socket(int domain, int type, int protocol);
sock_t sock = socket(AF_INET, SOCK_STREAM, 0);
if( sock < 0 )
{
    perror( "socket failed" );
    exit( EXIT_FAILURE );
}

// if wanting to set any socket options (setsockopt())
// this is the place to do so

struct sockaddr_in server;
memset(&server, 0, sizeof(server));

server.sin_family      = AF_INET;
server.sin_addr.s_addr = inet_addr( INADDR_ANY ); 
server.sin_port        = htons(8080);  


if( bind( sock, (struct sockaddr*) &server, sizeof(server) ) ) 
{
    perror( "bind() failed" );
    close( sock );
    exit( EXIT_FAILURE );
}

if( listen(sock, 5) )
{
    perror( "listen failed" );
    exit( EXIT_FAILURE );
}

struct sockaddr_in client;
size_t len = sizeof( client ); 

while(1)
{
    sock_t clientSock = accept(sock, &client, &len); 
    if( clientSock <  0 )
    {
        perror( "accept failed" );
        continue;
    }

    // handle client connection
    close( clientSock );
}


close( sock );

Note: for long term consistency, the computer running this code needs to have a 'static' IP address, not a 'dynamic' IP address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM