Getting the IP address of the current machine using Java

后端 未结 17 1760
眼角桃花
眼角桃花 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: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.

提交回复
热议问题