Domanda

I have some existing code that worked fine under Windows 2003, to obtain the list of IP addresses bound to the server:

foreach (IPAddress addr in (Dns.GetHostEntry(Dns.GetHostName())).AddressList)
{
    // Code here to act on each address
}

When I run this code on our Windows 2008 server, it only returns one IP address. Upon further investigation, it seems all of the rest of the IP addresses that the machine is listening on were added using the netsh int ipv4 add address command and specifying the skipassource=true flag.

Is there a way to include those addresses in my query, i.e. return ALL addresses on the server?

(If you're curious, the skipassource=true flag was set because Windows 2008 introduced new behavior in networking that allows it to decide which of your IP addresses it considers "primary," and the rest of our applications rely on us being able to choose the primary. The only way to do that in Windows 2008 is to mark all other addresses as skipassource=true.)

Edit This question is now just to satisfy my curiosity, as I have worked around the problem. My original code above was used to run through all the IPs on the server, and see if it found a match to a specific IP I was looking for. I now check to see if the server I'm on is already running a service that listens to that specific IP address/port, so I no longer need to loop through ALL of the IPs. Still, I would be interested to hear if there is an answer to the original question.

Edit Thanks to @aKzenT for the solution on this. I now use NetworkInteface.GetAllNetworkInterfaces() to get access to all the IPs, rather than Dns.GetHostEntry(). My final code looks like this:

foreach (NetworkInterface netface in NetworkInterface.GetAllNetworkInterfaces())
{
    foreach (UnicastIPAddressInformation uni in netface.GetIPProperties().UnicastAddresses)
    {
        IPAddress addr = uni.Address;
        // Code here to act on each address
    }
}
È stato utile?

Soluzione

skipassource is intended to not include an ip address in the DNS name system, so I think you have to find another way than Dns.GetHostEntry

Did you try looking at the System.Net.NetworkInformation namespace?

I think if you loop through the adapters via GetAllNetworkInterfaces then call GetIPProperties to get the IP properties of the adapter and then check the UnicastAddresses you can built a list of IP addresses. Not tested though.

See also: http://msdn.microsoft.com/de-de/library/system.net.networkinformation.networkinterface.getallnetworkinterfaces.aspx

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top