c++ - WinSock2 sockaddr structure as a parameter -
what point of having functions such inet_ntop, wsaaddresstostring, recvfrom require either size of actual sockaddr structure or address family provided?
the first 2 bytes of sockaddr structure indicate address family , therefore indicate whether it's sockaddr_in or sockaddr_in6.
so reason additional sizeof(sockaddr_in/sockaddr_in6) , af_inet/af_inet6?
sockaddr
legacy type. there newer sockaddr_...
types specific address families, sockaddr_in
ipv4 , sockaddr_in6
ipv6, , have different byte sizes. apis operate on generic sockaddr*
pointers partly historic reasons , partly flexibility. socket apis recognize multiple address types. have provide sizes apis can validate memory buffers large enough pass address data based on specified families (af_inet
ipv4, af_inet6
ipv6).
in inet_ntop()
, in_addr
, in6_addr
not contain address family, why have pass separately. responsible making sure specify correct address family input type passing in.
in wsaaddresstostring()
, sockaddr*
pointer input buffer. have pass allocated size of buffer. instance, since sockaddr_in
smaller sockaddr_in6
, if allocate sockaddr_in
set family af_inet6
instead of af_inet
, buffer small function access of ipv6 fields, fail wsaefault
error instead of crashing.
in recvfrom()
, sockaddr*
pointer output buffer. have preallocate , pass allocated size. if allocate sockaddr_in
receive ipv6 packet, sender's address not fit in buffer , function fail wsaefault
error.
Comments
Post a Comment