Search code examples
carrayssocketsudpip-address

Extracting IP Address and Port Info from sockaddr_storage


I'm currently working on a UDP server that receives a request from a client. The datagram I receive is a byte (char) array 5 elements long, with the final two elements being a port number.

Eventually this server will have to return both the IP address and the port number in a datagram of its own.

I already know how to use inet_ntop and the sockaddr struct I've connected with and received from to print out the ip, but it returns a string that's not in the format I want. For instance:

string1 = inet_ntop(their_addr.ss_family,get_in_addr(
    (struct sockaddr *)&their_addr),s, sizeof s);

returns:

127.0.0.1

or:

[1][2][7][.][0][.][0][.][1]

when I need something like:

[127][0][0][1]

Should I be using some sort of character and array manipulation to make my 4-element byte array? Or does a sockaddr have this information in a way that I can leave it in this hex form and return it?


Solution

  • Assuming for IPv4.

    After taking the address of your sockaddr_storage or sockaddr structure and casting it to the IPv4 version sockaddr_in, you can then access the individual bytes of the IPv4 address.

    struct sockaddr_in *sin = (struct sockaddr_in *)&their_addr;
    

    Then you can take address of the s_addr member which is a 32 bit value (in_addr_t) that holds the 4 bytes of the ip address (in network byte order) and cast it to a pointer to an unsigned char which then lets you access the individual bytes of the value.

    unsigned char *ip = (unsigned char *)&sin->sin_addr.s_addr;
    
    printf("%d %d %d %d\n", ip[0], ip[1], ip[2], ip[3]);