Here you can find the source of getPublicIPAddress()
Parameter | Description |
---|---|
Exception | an exception |
public static String getPublicIPAddress() throws Exception
//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; } }