开发者

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

开发者 https://www.devze.com 2022-12-08 01:18 出处:网络
I\'m trying to find the magical answer to the \"what\'s the primary IP address\" of a system. My research has determined that the answer to \"best\" means this:

I'm trying to find the magical answer to the "what's the primary IP address" of a system. My research has determined that the answer to "best" means this:

  1. Look at [system.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() for interfaces with default gateways assigned. If you only find one, then you are done.
  2. If there's more than one, you have to look at the routing table for the one wi开发者_运维技巧th the lowest metric (look at the 0.0.0.0 network entries).
  3. In case of a tie in the metric, the adapter with the lowest binding order wins.

My question is: how do you determine the binding order using .NET? I've seen a solution that looks at the registry and that's alright, but I was hoping for a prettier interface.

Bonus points for PowerShell samples as that's my language of choice. :)


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


An alternative, registry based solution exists here.


A good starting point seems to be this API method: EnumBindingPaths, but it requires C++ or C#/VB + P/Invoke knowledge to use that method and its helpers. In Microsoft KB article 894564, this and some other approaches are suggested to find or manipulate the binding. The method may not work on Vista/w7, but I'm not sure.

It will be some work to get from this API method to PowerShell. The method itself probably uses the registry internally, not sure if it really gives an advantage over your current approach.


Try this:

$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

精彩评论

暂无评论...
验证码 换一张
取 消