Determining the local intranet ip address in .NET

5.2k views Asked by At

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

I have tried getting all the IPs and filtering by 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 this seems a bit magic to me, i'd rather .net did the work, it also returns multiple ips due to me having VirtualBox installed

I have 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 does work, but would it work on other network configurations?

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

Has anyone got a better way?

1

There are 1 answers

0
BenSwayne On BEST ANSWER

You can't reliably use a single IP as the machine could have multiple network cards or multiple IPs per network card. For example my laptop has both a wired network card and a wireless network card and is quite happy to grab two local IPs from my router via DHCP.

Also in some fancy network setups (mostly corporate environments) you can have IP with different subnets able to talk to each via a router. I might have floor #6 in an office tower be 192.168.6.X and floor number 7 be 192.168.7.X and then have a router allow traffic across multiple subnets despite them being masked apart by the subnet mask.

A better strategy would be to grab the list of local IPs, filter for loopback addresses (127.0.0.1) and then attempt to connect to the target machine.

But if you just want to detect a local IP as "not public on the internet", you can attempt to ping a public address (maybe your webserver?) with a time-to-live (TTL) of 1 hop. This won't make it past any router if one is present, meaning it will fail if it can't reach the public internet in 1 hop or less indicating that it is behind a firewall.

Check out this great answer on stackoverflow which includes source code: Check if IP is in LAN (behind firewalls and routers)