Reputation: 3956
How can one get the default IP address excluding the 127.0.0.1 loopback address when mutliple IP addresses are assigned to PC i.e if the PC is multihomed.
Following code returns correct default IP address on one PC but returns incorrect IP address on another PC, so there must be some other solution.
private string[] GetDefaultIPWithSubnet()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
string[] ipSubnet = new string[2];
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
try
{
string[] ips = (string[])mo["IPAddress"];
string[] subnets = (string[])mo["IPSubnet"];
ipSubnet[0] = ips[0].ToString();
ipSubnet[1] = subnets[0].ToString();
break;
}
catch (Exception ex)
{
return null;
}
}
}
return ipSubnet;
}
Upvotes: 0
Views: 6207
Reputation: 20775
public static void GetDefaultIp()
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
if (adapter.OperationalStatus == OperationalStatus.Up && adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
foreach (var x in properties.UnicastAddresses)
{
if (x.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
Console.WriteLine(" IPAddress ........ : {0:x}", x.Address.ToString());
}
}
}
}
Upvotes: 4
Reputation: 5415
I think you mean the interface with the default route. You can get the IPv4 route table with the GetIpForwardTable function (quick google reveals that it is callable through p/invoke) and look for a 0.0.0.0 destination route (run route print
at command line to check what a route table looks like).
Upvotes: 3
Reputation: 3131
I think you misunderstood the meaning of IPEnabled, as far as I know that parameter is TRUE if TCP/IP is enabled on the interface. So I don't think this is what you're looking for.
Upvotes: 0