joebalt
joebalt

Reputation: 989

NetAddresses always null in Win32_NetworkAdapter query

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

Answers (3)

jwsadler
jwsadler

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

user645280
user645280

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

Polynomial
Polynomial

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:

  1. Order your adapters by metric, lowest first.
  2. Prioritise WAN IPs, then 192.168.x.x, then 10.x.x.x, and totally ignore loopback addresses.

This will give you a guess as to the "preferred" address, though it's hardly definitive.

Upvotes: 1

Related Questions