views:

380

answers:

2

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 with 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. :)

+1  A: 

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...

Reed Copsey
+1  A: 

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.

Abel