Understanding struct sockaddr

妖精的绣舞 提交于 2019-11-27 12:59:01

问题


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?


回答1:


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 https://beej.us/guide/bgnet/html/multi/sockaddr_inman.html. 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:

  • http://en.wikipedia.org/wiki/AF_INET
  • http://msdn.microsoft.com/en-us/library/ms740496(v=vs.85).aspx
  • http://www.iana.org/assignments/address-family-numbers/address-family-numbers.xml



回答2:


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.



来源:https://stackoverflow.com/questions/7414943/understanding-struct-sockaddr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!