Sunday, February 23, 2014

Socket Address Structure

The socket API specifies a generic data type called sockaddr for used by API calls.

struct sockaddr {
    sa_family_t sa_family;  // address family e.g. AF_INET or AF_INET6
    char sa_data[14];    // address info - A blob of bits to handle diff OS and network
};

Note that this sockaddr structure is not large enough to handle a IPV6 address which is 16 bytes long.

The actual data structure used in socket call are sockaddr_in (for IPV4) and sockaddr_in6 (for IPV6).  The structure is casted with (struct sockaddr *) when used.

struct in_addr { uint32_t s_addr; }; // 4-byte IPV4 address
struct sockadr_in {
    sa_family_t sin_family;  //address family IPV4
    in_port_t sin_port;    //16-bit port
    struct in_addr sin_addr;
    char sin_zero[8];    //padding
};

No comments: