c++ - What's the difference between sockaddr, sockaddr_in, and sockaddr_in6? -


i know sockaddr_in ipv4, , sockaddr_in6 ipv6. confusion me difference between sockaddr , sockaddr_in[6].

some functions accept sockaddr , functions accept sockaddr_in or sockaddr_in6, so:

  • what's rule?
  • and why there need 2 different structures?

and because sizeof(sockaddr_in6) > sizeof(sockaddr) == sizeof(sockaddr_in).

  • does mean should use sockaddr_in6 allocate memory in stack , cast sockaddr , sockaddr_in if need support ipv4 , ipv6?

one example is: have socket, , want string ip address of (it can ipv4 or ipv6).

we first call getsockname addr , call inet_ntop based on addr.sa_family.

is there wrong code snippet?

sockaddr_in6 addr_inv6; sockaddr* addr = (sockaddr*)&addr_inv6; sockaddr_in* addr_in = (sockaddr_in*)&addr_inv6;  socklen_t len = sizeof(addr_inv6); getsockname(_socket, addr, &len); char ipstr[256]; if (addr->sa_family == af_inet6) {     inet_ntop(addr_inv6.sin6_family, &addr_inv6.sin6_addr, ipstr, sizeof(ipstr));      // <<<<<<<<is line valid, getsockname expected sockaddr, use output parameter sockaddr_in6. } else {     inet_ntop(addr_in->sin_family, &addr_in->sin_addr, ipstr, sizeof(ipstr)); } 

sockaddr_in , sockaddr_in6 both structures first member sockaddr structure.

according c standard, address of structure , first member same, can cast pointer sockaddr_in(6) in pointer sockaddr.

functions taking sockaddr_in(6) parameter may modify sockaddr part, , functions taking sockaddr parameter care part.

it's bit inheritance.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

IIS->Tomcat Redirect: multiple worker with default -