Determining the local intranet IP address in .NET.

I am trying to get the local intranet of an ip machine from code running on this machine Is there a specific way to do this?

I tried to get all IP addresses and filter 10.0.0.0-10.255.255.255,172.16.0.0-172.31.255.255,192.168.0.0-192.168.255.255

Dns.GetHostEntry(Dns.GetHostName()).AddressList 

but for me it seems a little magical, I would prefer .net to do the job, it also returns a few ips due to the fact that I have VirtualBox installed

I also tried the following

 var localAddress = ( from ni in NetworkInterface.GetAllNetworkInterfaces() where ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && hostEntry.HostName.EndsWith(string.Concat(".", ni.Name)) let props = ni.GetIPProperties() from unicastAddress in props.UnicastAddresses where unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork select unicastAddress.Address).FirstOrDefault(); 

which works, but will it work with other network configurations?

this bit concerns me hostEntry.HostName.EndsWith(string.Concat(".", ni.Name))

Has anyone got a better way?

+4
source share
1 answer

You cannot reliably use a single IP address, because a computer can have several network cards or several IP addresses per network card. For example, my laptop has both a wired network card and a wireless network card, and I’m quite happy to capture two local IP addresses from my router via DHCP.

Also, in some fancy network settings (mainly corporate environments), you can have an IP address with different subnets that can talk to everyone through a router. I can have floor number 6 in the office tower 192.168.6.X, and number 7 is 192.168.7.X, and then the router allows traffic through several subnets, despite the fact that they are masked in the subnet mask.

The best strategy would be to grab a list of local IP addresses, filter loopback addresses (127.0.0.1), and then try to connect to the target machine.

But if you just want to define the local IP address as β€œnot publicly accessible on the Internet”, you can try to ping the address (maybe your web server?) With a lifetime (TTL) of 1 hop. This will not pass by any router if it is present, that is, it will not work if it cannot reach the public Internet in 1 hp or less, indicating that it is behind the firewall.

Check out this great stackoverflow answer, which includes the source code: Check if the IP address is on the local network (behind firewalls and routers)

+3
source

All Articles