Getting the IP address of the current machine using Java

后端 未结 17 1771
眼角桃花
眼角桃花 2020-11-22 02:26

I am trying to develop a system where there are different nodes that are run on different system or on different ports on the same system.

Now all the nodes create

相关标签:
17条回答
  • 2020-11-22 03:07
    private static InetAddress getLocalAddress(){
            try {
                Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
                while( b.hasMoreElements()){
                    for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
                        if ( f.getAddress().isSiteLocalAddress())
                            return f.getAddress();
                }
            } catch (SocketException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    0 讨论(0)
  • 2020-11-22 03:11

    This is a working example of the ACCEPTED answer above! This NetIdentity class will store both the internal host ip, as well as the local loopback. If you're on a DNS based server, as mentioned above, you may need to add some more checks, or possible go the Configuration File Route.

    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Enumeration;
    
    /**
     * Class that allows a device to identify itself on the INTRANET.
     * 
     * @author Decoded4620 2016
     */
    public class NetIdentity {
    
        private String loopbackHost = "";
        private String host = "";
    
        private String loopbackIp = "";
        private String ip = "";
        public NetIdentity(){
    
            try{
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    
                while(interfaces.hasMoreElements()){
                    NetworkInterface i = interfaces.nextElement();
                    if(i != null){
                        Enumeration<InetAddress> addresses = i.getInetAddresses();
                        System.out.println(i.getDisplayName());
                        while(addresses.hasMoreElements()){
                            InetAddress address = addresses.nextElement();
                            String hostAddr = address.getHostAddress();
    
                            // local loopback
                            if(hostAddr.indexOf("127.") == 0 ){
                                this.loopbackIp = address.getHostAddress();
                                this.loopbackHost = address.getHostName();
                            }
    
                            // internal ip addresses (behind this router)
                            if( hostAddr.indexOf("192.168") == 0 || 
                                    hostAddr.indexOf("10.") == 0 || 
                                    hostAddr.indexOf("172.16") == 0 ){
                                this.host = address.getHostName();
                                this.ip = address.getHostAddress();
                            }
    
    
                            System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress());
                        }
                    }
                }
            }
            catch(SocketException e){
    
            }
            try{
                InetAddress loopbackIpAddress = InetAddress.getLocalHost();
                this.loopbackIp = loopbackIpAddress.getHostName();
                System.out.println("LOCALHOST: " + loopbackIp);
            }
            catch(UnknownHostException e){
                System.err.println("ERR: " + e.toString());
            }
        }
    
        public String getLoopbackHost(){
            return loopbackHost;
        }
    
        public String getHost(){
            return host;
        }
        public String getIp(){
            return ip;
        }
        public String getLoopbackIp(){
            return loopbackIp;
        }
    }
    

    When I run this code I actually get a print out like this:

        Software Loopback Interface 1
            -127.0.0.1:127.0.0.1 - [B@19e1023e
            -0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
    Broadcom 802.11ac Network Adapter
            -VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4
            -fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
    Microsoft Kernel Debug Network Adapter
    Intel Edison USB RNDIS Device
    Driver for user-mode network applications
    Cisco Systems VPN Adapter for 64-bit Windows
    VirtualBox Host-Only Ethernet Adapter
            -VIKING:192.168.56.1 - [B@3cd1f1c8
            -VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d
    LogMeIn Hamachi Virtual Ethernet Adapter
            -VIKING:25.113.118.39 - [B@1996cd68
            -VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e
            -VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590
    Bluetooth Device (Personal Area Network)
            -fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde
    Bluetooth Device (RFCOMM Protocol TDI)
    Intel(R) Ethernet Connection (2) I218-V
            -fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017
    Microsoft Wi-Fi Direct Virtual Adapter
            -fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25
    VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000
    VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000
    VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001
    VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002
    VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000
    VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003
    VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000
    VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004
    VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
    VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005
    Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000
    Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000
    Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001
    Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000
    Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002
    Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000
    Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003
    Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000
    Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004
    Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000
    Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005
    Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000
    Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000
    Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000
    Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003
    Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000
    Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004
    Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000
    Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005
    Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000
    Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006
    Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
    Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007
    Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000
    Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000
    Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002
    Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000
    Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003
    Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000
    Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004
    Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
    Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005
    Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
    Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006
    

    For my use I'm setting up a Upnp Server, it helped to understand the 'pattern' that i was looking for. Some of the objects returned are Ethernet Adapters, Network Adapters, Virtual Network Adapters, Drivers, and VPN Client Adapters. Not everything has an Address either. So you'll want to skip out on interface objects that don't.

    You can also add this to the loop for the current NetworkInterface i

    while(interfaces.hasMoreElements()){
        Enumeration<InetAddress> addresses = i.getInetAddresses();
        System.out.println(i.getDisplayName());
        System.out.println("\t- name:" + i.getName());
        System.out.println("\t- idx:" + i.getIndex());
        System.out.println("\t- max trans unit (MTU):" + i.getMTU());
        System.out.println("\t- is loopback:" + i.isLoopback());
        System.out.println("\t- is PPP:" + i.isPointToPoint());
        System.out.println("\t- isUp:" + i.isUp());
        System.out.println("\t- isVirtual:" + i.isVirtual());
        System.out.println("\t- supportsMulticast:" + i.supportsMulticast());
    }
    

    And You'll see information in your output much like this:

    Software Loopback Interface 1
        - name:lo
        - idx:1
        - max trans unit (MTU):-1
        - is loopback:true
        - is PPP:false
        - isUp:true
        - isVirtual:false
        - supportsMulticast:true
            -ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e
            -ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
    Broadcom 802.11ac Network Adapter
        - name:wlan0
        - idx:2
        - max trans unit (MTU):1500
        - is loopback:false
        - is PPP:false
        - isUp:true
        - isVirtual:false
        - supportsMulticast:true
            -ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4
            -ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
    Microsoft Kernel Debug Network Adapter
        - name:eth0
        - idx:3
        - max trans unit (MTU):-1
        - is loopback:false
        - is PPP:false
        - isUp:false
        - isVirtual:false
        - supportsMulticast:true
    
    0 讨论(0)
  • 2020-11-22 03:11

    Since my system (like so many other systems) had various network interfaces.InetAddress.getLocalHost() or Inet4Address.getLocalHost() simply returned one that I did not desire. Therefore I had to use this naive approach.

    InetAddress[] allAddresses = Inet4Address.getAllByName("YourComputerHostName");
            InetAddress desiredAddress;
            //In order to find the desired Ip to be routed by other modules (WiFi adapter)
            for (InetAddress address :
                    allAddresses) {
                if (address.getHostAddress().startsWith("192.168.2")) {
                    desiredAddress = address;
                }
            }
    // Use the desired address for whatever purpose.
    

    Just be careful that in this approach I already knew that my desired IP address is in 192.168.2 subnet.

    0 讨论(0)
  • 2020-11-22 03:14

    Example in scala (useful in sbt file):

      import collection.JavaConverters._
      import java.net._
    
      def getIpAddress: String = {
    
        val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq
    
        val ipAddresses = enumeration.flatMap(p =>
          p.getInetAddresses.asScala.toSeq
        )
    
        val address = ipAddresses.find { address =>
          val host = address.getHostAddress
          host.contains(".") && !address.isLoopbackAddress
        }.getOrElse(InetAddress.getLocalHost)
    
        address.getHostAddress
      }
    
    0 讨论(0)
  • 2020-11-22 03:14

    You can use java.net.InetAddress API. Try this :

    InetAddress.getLocalHost().getHostAddress();
    
    0 讨论(0)
  • 2020-11-22 03:20

    firstly import the class

    import java.net.InetAddress;
    

    in class

      InetAddress iAddress = InetAddress.getLocalHost();
      String currentIp = iAddress.getHostAddress();
      System.out.println("Current IP address : " +currentIp); //gives only host address
    
    0 讨论(0)
提交回复
热议问题