I can't find code to find the proper IP address to use to open a TCP/IP server port on my machine.
The problem occurs because I have many network adapters. I have some Virtual Machine(s) (for example: HyperV / VirtualBox / VmWare) which create virtual network adapter and each one has its one IPAddress. So how to avoid those IPAddress (proper network card) and find the only one used to access the internet for real?
When I try to find the proper IP Address, I get the virtual network adapter card Ip Adress instead of the physical one using this code:
IPAddress properIpAddress = null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in interfaces)
{
var ipProps = networkInterface.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((networkInterface.OperationalStatus == OperationalStatus.Up) && (ip.Address.AddressFamily == AddressFamily.InterNetwork))
{
if (ip.Address.ToString() == "127.0.0.1")
{
continue;
}
properIpAddress = ip.Address;
// Console.Out.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
Debug.WriteLine(ip.Address.ToString() + "|" + networkInterface.Description.ToString());
break;
}
}
if (properIpAddress != null)
{
break;
}
}
The real solution is to not search for an adapter in the first place.
Just use IPAddress.Any
to listen on all interfaces at the given port.
using(TcpListener tcpListener = new TcpListener(IPAddress.Any, somePortNumber))
{
// some code
}