Java IP Address Get getPublicIPAddress()

Here you can find the source of getPublicIPAddress()

Description

This function returns the first external IP address encountered

License

Apache License

Exception

Parameter Description
Exception an exception

Return

IP address or null

Declaration

public static String getPublicIPAddress() throws Exception 

Method Source Code

//package com.java2s;
/*//from   w  ww  .  ja  v  a  2s.  c  om
 Copyright 2014 Groupon, Inc.
    
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

import java.net.InetAddress;
import java.net.NetworkInterface;

import java.util.Enumeration;

public class Main {
    /**
     * This function returns the first external IP address encountered
     *
     * @return IP address or null
     * @throws Exception
     */
    public static String getPublicIPAddress() throws Exception {
        final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";

        String ipAddr = null;
        Enumeration e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();

                // Pick the first non loop back address
                if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) || i.getHostAddress().matches(IPV4_REGEX)) {
                    ipAddr = i.getHostAddress();
                    break;
                }
            }
            if (ipAddr != null) {
                break;
            }
        }

        return ipAddr;
    }
}

Related

  1. getPublicIP()
  2. getPublicIP()
  3. getPublicIP()
  4. getPublicIP()
  5. getPublicIP2()
  6. getPublicIps()
  7. getPublicIpViaHttp()
  8. getStrLocalIP()
  9. getVisibleIp()