Josh707 Josh707 - 4 years ago 358
C# Question

Get name of network that a network interface is connected to

In Windows Control Panel, you can find a list of network interfaces/connections which displays the following:

network interfaces

In the .NET framework these are represented in the

class (and found via

For reference, say I'm reading properties from the Ethernet interface - the
property returns
, the
property returns
"Realtek PCIe FE Family Controller"

However, nothing in the class seems to be able to get me the name of the network it's connected to (in this case
). How would I go about getting that string? I have to know what network the interface is associated with, not just a list of the networks that exist.

Answer Source

It turns out information about each network is stored as a 'network profile' by Windows, storing it's name and other info like whether it's public or not. The name can be changed by users in the control panel, but in my situation that's not a problem.

The Windows API Code Pack from Microsoft contains the APIs necessary to get the collection of network profiles. As it contains a lot of bloat that I don't need, the bare minimum code to wrap the Windows API can be found here.

A collection of the network profiles can then be found like so:

//Get the networks that are currently connected to
var networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);

Each object in the collection represents a network profile and contains a collection of NetworkConnection objects. Each NetworkConnection object appears to be info about an interface's connection to the base network.

foreach(Network network in networks)
    //Name property corresponds to the name I originally asked about
    Console.WriteLine("[" + network.Name + "]");

    foreach(NetworkConnection conn in network.Connections)
        //Print network interface's GUID
        Console.WriteLine("\t\t" + conn.AdapterId.ToString());

The NetworkConnection.AdapterId property is the same network interface GUID that the NetworkInterface.Id property knows.

So, you can determine what network an interface is connected to, by checking if one of the network's connections have the same ID as the interface. Note that they're represented differently, so you'll have to do a bit more work:

example image

Both my Wi-Fi and Ethernet interfaces are connected to the BELL024 network in the above example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download