tags:

views:

53

answers:

0

I am trying to do a Socket.Connect() and when the IP address that i specify is in ipv6 format, the Socket.Connect() fails with the error message :

Address family not supported by protocol family. An address incompatible with the requested protocol was used. All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM). This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.

However if i uncomment the code in the below snippet, then the ipv4 address would be used to connect and now the call succeeds; Note that hostadd.AddressList[0] returns a ipv6 address. Also note that i am connecting between Windows 7 64 bit machines which both have ipv4 and ipv6 enabled;

Why does connecting using an ipv6 address throw the error? The Socket.Connect() method documents that :

If IPv6 is enabled and the Connect(String, Int32) method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address.is not listening on the IPv6 address.

                IPHostEntry hostadd = Dns.GetHostEntry(TimeServer);
                IPAddress ip4IP = hostadd.AddressList[0];
                //foreach (IPAddress ipAddress in hostadd.AddressList) {
                //    if (ipAddress.AddressFamily == AddressFamily.InterNetwork) {
                //        ip4IP = ipAddress;
                //        break;
                //    }
                //}
                IPEndPoint EPhost = new IPEndPoint(ip4IP, 123);

                Socket pSocket = new Socket(
                    AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                pSocket.ReceiveTimeout = 2000;
                pSocket.SendTimeout = 2000;
                pSocket.Connect(EPhost);