Getting the IP address of the current machine using Java

后端 未结 17 1774
眼角桃花
眼角桃花 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 02:57

    A rather simplistic approach that seems to be working...

    String getPublicIPv4() throws UnknownHostException, SocketException{
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        String ipToReturn = null;
        while(e.hasMoreElements())
        {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements())
            {
                InetAddress i = (InetAddress) ee.nextElement();
                String currentAddress = i.getHostAddress();
                logger.trace("IP address "+currentAddress+ " found");
                if(!i.isSiteLocalAddress()&&!i.isLoopbackAddress() && validate(currentAddress)){
                    ipToReturn = currentAddress;    
                }else{
                    System.out.println("Address not validated as public IPv4");
                }
    
            }
        }
    
        return ipToReturn;
    }
    
    private static final Pattern IPv4RegexPattern = Pattern.compile(
            "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
    
    public static boolean validate(final String ip) {
        return IPv4RegexPattern.matcher(ip).matches();
    }
    

提交回复
热议问题