33
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?

roschach
  • 8,390
  • 14
  • 74
  • 124
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

2 Answers2

31

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:

Alex Shroyer
  • 3,499
  • 2
  • 28
  • 54
Len Holgate
  • 21,282
  • 4
  • 45
  • 92
  • Thanks, but then why in this case address size is *fixed* 14 `sa_data[14]`? – Aquarius_Girl Sep 16 '11 at 08:07
  • 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? – Aquarius_Girl Sep 16 '11 at 08:28
  • 1
    See http://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. – O.C. Sep 16 '11 at 11:51
  • @OrcunC Thanks, so you mean that 14 bytes is the "maximum" `ANY` socket address can be? – Aquarius_Girl Sep 16 '11 at 12:48
  • 5
    No - IPv6 addresses are 16 bytes. In the past it was an arbitrary maximum, but it was for convenience rather than a hard limit. – Remy Sep 28 '11 at 20:38
  • 2
    MSDN is not authoritative for Posix. Refer to the Posix specs rather than vendor specific documentation: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_socket.h.html and http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/netinet_in.h.html – Michael Beer Dec 07 '18 at 09:11
  • 1
    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 – Michael Beer Dec 07 '18 at 09:17
  • 1
    working link to beej's http://beej.us/guide/bgnet/html/#structs – Nilesh Deokar Oct 27 '19 at 16:47
-1

I found this out when trying to duplicate the jnetpcap getHardwareAddress() method in C/C++. The MAC address is contained, when sa_family is 17 (0x11, AF_PACKET), in bytes 10-15.

Jerry Miller
  • 921
  • 1
  • 8
  • 11