protected void DoBind(Socket socket, string host, int port)
{
IPAddress ipaddress;
try
{
if(TryParseIPAddress(host, out ipaddress))
{
TryBindSocket(socket, ipaddress, port);
}
else
{
// Looping through the AddressList allows different type of connections to be tried
// (IPv6, IPv4 and whatever else may be available).
IPHostEntry hostEntry = GetIPHostEntry(host);
if(null != hostEntry)
{
// Prefer IPv6 first.
ipaddress = GetIPAddress(hostEntry, AddressFamily.InterNetworkV6);
if(!TryBindSocket(socket, ipaddress, port))
{
// Try IPv4 next.
ipaddress = GetIPAddress(hostEntry, AddressFamily.InterNetwork);
if(!TryBindSocket(socket, ipaddress, port))
{
// Try whatever else there is.
foreach(IPAddress address in hostEntry.AddressList)
{
if(AddressFamily.InterNetworkV6 == address.AddressFamily
|| AddressFamily.InterNetwork == address.AddressFamily)
{
// Already tried these protocols.
continue;
}
if(TryBindSocket(socket, ipaddress, port))
{
ipaddress = address;
break;
}
}
}
}
}
}
if(!socket.IsBound)
{
throw new SocketException();
}
}
catch(Exception ex)
{
throw new NMSConnectionException(String.Format("Error binding to {0}:{1}.", host, port), ex);
}
Tracer.DebugFormat("Bound to {0}:{1} using.", host, port);
}