Reputation: 989
I am trying to get the active network adapter's IP address, so that I avoid virtual and other VPN adapters that are not connected at present.
On my current laptop the following code returns 3 IP V4 addresses, and I don't know how to get the "real", in use IP address from that list.
IPAddress[] ipV4Addresses = Array.FindAll(
Dns.GetHostEntry(String.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
Looking at MSDN doc here, I thought maybe I was on the right track. Has anyone obtained the list of IP addresses per adapter successfully? If so, please share your wisdom. Thanks!
This is all prototype at this point. I have this code (thanks to SO!), and the string[] netAddresses is always null, even with the computer connected to a network and with a functioning IP address.
string wmiQuery = "SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection moCollection = moSearch.Get();
foreach (ManagementObject mo in moCollection)
{
Console.WriteLine("{0} is {1}", mo["Name"], mo["NetConnectionStatus"]);
string[] netAddresses = (string[])mo["NetworkAddresses"];
if (netAddresses != null)
{
foreach (string netAddress in netAddresses)
{
Console.WriteLine("\tnet addresses:");
Console.WriteLine("\t\t{0}", netAddress);
}
}
}
Upvotes: 2
Views: 3086
Reputation: 471
Look at WIn32_NetworkAdapterConfiguration, by using the InterfaceIndex from Win32_NetworkAdapter you should be able to get the configuration you need with the ipaddresses assigned to that nic.
Upvotes: 1
Reputation:
from MS docs: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216%28v=vs.85%29.aspx
NetworkAddresses
Data type: string array Access type: Read-only
Array of network addresses for an adapter. This property is inherited from CIM_NetworkAdapter.
This property has not been implemented yet. It returns a NULL value by default.
Upvotes: 3
Reputation: 28316
There's no such thing as a "real" IP address. Each packet you send is routed to its destination based on the metric of the adapter and the available routing paths. You can guess which IP is primarily being used for internet traffic by doing the following:
This will give you a guess as to the "preferred" address, though it's hardly definitive.
Upvotes: 1