user128176
user128176

Reputation: 23

How to get client IP by the socket number in C

I'm writing a simple client-server code in C. i was asked for the server to print the IP address of the client that connected to it. However, i can't seem to find a way to know the client's IP address from the server console. Is there a way to do that?

// Initialize Winsock.
if ( StartupRes != NO_ERROR )
{
    printf( "error %ld at WSAStartup( ), ending program.\n", WSAGetLastError() );
    // Tell the user that we could not find a usable WinSock DLL.                                  
    return;
}

/* The WinSock DLL is acceptable. Proceed. */

// Create a socket.    
MainSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

if ( MainSocket == INVALID_SOCKET ) 
{
    printf( "Error at socket( ): %ld\n", WSAGetLastError( ) );
    return;
}

// Create a sockaddr_in object and set its values.
// Declare variables

Address = inet_addr(CHANNEL_IP);
if ( Address == INADDR_NONE )
{
    printf("The string \"%s\" cannot be converted into an ip address. ending program.\n",
            CHANNEL_IP);
    return;
}
service.sin_family = AF_INET;
service.sin_addr.s_addr = Address;
service.sin_port = htons(clientinfo->senderPort);

//Bind the socket
bindRes = bind( MainSocket, ( SOCKADDR* ) &service, sizeof( service ) );
if ( bindRes == SOCKET_ERROR ) 
{
    printf( "Channel-bind( ) failed with error %ld. Ending program\n", WSAGetLastError( ) );
    return;
}

 // Listen on the Socket.
ListenRes = listen( MainSocket, SOMAXCONN );
if ( ListenRes == SOCKET_ERROR ) 
{
    printf( "Failed listening on socket, error %ld.\n", WSAGetLastError() );
    return;
}
printf("Channel waiting for sender to connect...\n");

//Accepting connection
SenderSocket = accept( MainSocket, NULL, NULL );
    if ( SenderSocket == INVALID_SOCKET ){
        printf( "Accepting connection with client failed, error %ld\n", WSAGetLastError() ) ; 
        return;}
    else
        printf( "Sender Connected.\n" );

Upvotes: 1

Views: 6429

Answers (1)

dbush
dbush

Reputation: 224972

You need to pass in non-null values for the second and third parameters to accept:

struct sockaddr_in client_addr;
socklen_t slen = sizeof(client_addr);
SenderSocket = accept( MainSocket, (struct sockaddr *)&client_addr, &slen );

You can then get the client's IP and port from client_addr.

Upvotes: 5

Related Questions