How to determine the binding order of network interfaces in Windows using .NET?

I am trying to find a magic answer to the "primary IP address" of the system. My research has determined that the answer to "best" means this:

  • Take a look at [system.Net.NetworkInformation.NetworkInterface] :: GetAllNetworkInterfaces () for interfaces with default gateways assigned. If you only find it, then you are done.
  • If there are several, you need to look at the routing table for the one that has the lowest metric (look at the network entries 0.0.0.0).
  • In the case of binding to the metric, the adapter with the lowest binding order wins.

My question is: how do you determine the binding order using .NET? I saw a solution that looks at the registry and this is good, but I was hoping for a more beautiful interface.

Reward points for PowerShell samples as my language of choice. :)

+3
source share
3 answers

Personally, I see the Registry solution more elegant and reliable. The link you posted already uses PowerShell, so it seems like the perfect solution for you ...


An alternative registry solution exists here .

+2
source

API: EnumBindingPaths, ++ #/VB + P/Invoke. Microsoft KB 894564 . Vista/w7, .

, API PowerShell. , , , , .

+1

Try the following:

$IpAddress = (Test-Connection $env:computername -count 1).IPv4address.IPAddressToString

$NetworkAdapter = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter 'ipenabled = "true"'| where {$_.Ipaddress -contains $IpAddress}

$NetworkAdapter.properties| select -Property Name,Value
0
source

Source: https://habr.com/ru/post/1720196/


All Articles