GetHostEntry.AddressList

The common solution seems to be extracting element 0 and use that:

_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_EndPoint = new IPEndPoint(Dns.GetHostEntry(host).AddressList(0), Port);


This causes a SocketException when trying to use "localhost" in Windows Vista and Windows 7. The reason is that the first element is not of type InterNetwork. The cause is probably ipv6 but I've not investigated it further.

Assuming element 0 is a valid address without checking the other seems like a bad idea for anyone.


Here is my solution:

private IPAddress GetIPAddress(string host)
{
    foreach (IPAddress addr in Dns.GetHostEntry(host).AddressList) {
        if (addr.AddressFamily == AddressFamily.InterNetwork) {
            return addr;
        }
    }
   
    throw new SystemException("Invalid hostname.");
}
_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_EndPoint = new IPEndPoint(GetIPAddress(host), port);

0 kommentarer:

Post a Comment