Understanding struct sockaddr

98,288

The format and size of the address is usually protocol specific.

sockaddr is used as the base of a set of address structures that act like a discriminated union, see the Beej guide to networking. You generally look at the sa_family and then cast to the appropriate address family's specific address structure.

TCP and UDP do not have addresses specific to them as such, rather the IP level has different sizes of address for IPv4 and IPv6.

See also:

Share:
98,288

Related videos on Youtube

Aquarius_Girl
Author by

Aquarius_Girl

Arts and Crafts.stackexchange.com is in public beta now. Join us!

Updated on July 09, 2022

Comments

  • Aquarius_Girl
    Aquarius_Girl almost 2 years
    struct sockaddr {
        unsigned short sa_family;   // address family, AF_xxx
        char           sa_data[14]; // 14 bytes of protocol address
    };
    

    In this structure what exactly is the meaning address family depicted by sa_family?

    Does it mean that protocols like TCP/UDP have "addresses"? Well, the protocols can be identification numbers not addresses, I think.

    Anyway, if yes, then on what basis have their families been divided?

  • Aquarius_Girl
    Aquarius_Girl almost 13 years
    Thanks, but then why in this case address size is fixed 14 sa_data[14]?
  • Aquarius_Girl
    Aquarius_Girl almost 13 years
    and also, if the size is dependent on the type of protocol, then what is to be set there as a general case if protocol can be decided on run time?
  • O.C.
    O.C. almost 13 years
    See msdn.microsoft.com/en-us/library/ff570822%28v=vs.85%29.aspx. It states that the sockaddr structure is large enough to contain a transport address for most address families. So it is 14 bytes to make it large enough.
  • Aquarius_Girl
    Aquarius_Girl almost 13 years
    @OrcunC Thanks, so you mean that 14 bytes is the "maximum" ANY socket address can be?
  • Remy
    Remy over 12 years
    No - IPv6 addresses are 16 bytes. In the past it was an arbitrary maximum, but it was for convenience rather than a hard limit.
  • Michael Beer
    Michael Beer over 5 years
    MSDN is not authoritative for Posix. Refer to the Posix specs rather than vendor specific documentation: pubs.opengroup.org/onlinepubs/9699919799/basedefs/… and pubs.opengroup.org/onlinepubs/9699919799/basedefs/…
  • Michael Beer
    Michael Beer over 5 years
    Note in particular that there is no guarantee that sa_data has a minimum size. Instead, the sockaddr_storage should be used if you require space to hold any supported sockaddr incarnation
  • Nilesh Deokar
    Nilesh Deokar over 4 years
    working link to beej's beej.us/guide/bgnet/html/#structs