How to Determine Internet Network Interface in Java

后端 未结 4 808
再見小時候
再見小時候 2020-12-05 08:10

How do you determine which network interface is connected to the internet using Java? For example, I run

InetAddress.getLocalHost().getHostAddress();
         


        
4条回答
  •  粉色の甜心
    2020-12-05 08:43

    I was bugged by the same problem for a quite a bit and eventhough the inital question was asked ages ago I'll append my take on ths issue anyway. The ironic thing is that the answer was provided along with the question.
    It is: siteLocal = true
    Here is what worked for me

    1. Get all network interfaces

      NetworkInterface.getNetworkInterfaces();
      
    2. Single out those that are currently down (just reduces the number of runs)

      if(interface.isUp()){}
      
    3. Get the InetAddresses of the interfaces you just singled out

      interface.getInetAddresses();
      
    4. Check those addresses if they are site local addresses

      if(inetAddress.isSiteLocal()){}
      

    That should give you one/all InetAddress(es) - and the network interface(s) that is/are linked to your local network.
    Site local is defined to use addresses from these networks: 10.0.0.0, 172.16.0.0, 192.168.0.0 while VirtualBox adapters and others usually use the 169.254.0.0 link-local addresses. IPv6 also implements the site local concept, so it's best to focus on IPv4 here. On a regular end user machine this should work rather well and return just the one physical interface.

提交回复
热议问题