2

I am developing dual stack client-server communication. And I am curios: Do I have to open two sockets - one for IPv4 and one IPv6, or there is an option to open a socket for IPv6 and it will be able to work with both IPv4 and IPv6 connections? For example, if I open a socket like this:

  SOCKET sock = socket(AF_INET6, SOCK_STREAM, 0);

and then call

 int mode = 0;
  setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&mode, sizeof(mode));

Would it accept both IPv4 and IPv6 connections ? And if it will accept it, should I modify subsequent calls, to defining socket family and then do manipulation according to that family? something like:

  if (addr->ss_family == AF_INET)
  {

  }
  else if (addr->ss_family == AF_INET6)
  {

  }

Thanks on advance.

unresolved_external
  • 1,930
  • 5
  • 30
  • 65

1 Answers1

4

If you turn off IPV6_V6ONLY, you will get both IPv6 and IPv4-mapped IPv6 connections on the same socket. Thus you only have to open a single socket.

It is a very good idea to explicitly set this to the value you want, as the default varies between OSes and even between Linux kernel versions. (In Linux, it currently defaults to off, but was previously defaulted to on.)

Be aware that IPv4-mapped IPv6 addresses will appear in string format with a leading ::ffff:, e.g. ::ffff:203.0.113.47. Your application needs to be able to deal with this.

Michael Hampton
  • 9,737
  • 4
  • 55
  • 96