Java IP Address Get getPublicIP()

Here you can find the source of getPublicIP()

Description

get Public IP

License

Open Source License

Declaration

public static String getPublicIP() 

Method Source Code


//package com.java2s;
/* This file is part of Math4J.
 * Math4J is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.//  w w  w  .  j ava 2 s . com
 *
 * Math4J is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Math4J; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 * 
 * Copyright 2005 Anthony Magee
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.URL;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static String getPublicIP() {
        String result = "0.0.0.0";
        BufferedReader in = null;
        String inputLine = "";
        Pattern p = Pattern.compile("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b");
        // this matches ip addresses of the form ddd.ddd.ddd.ddd
        Matcher m = p.matcher("");

        try {
            URL ip = new URL("http://www.whatismyip.com/");
            in = new BufferedReader(new InputStreamReader(ip.openStream()));

            boolean found = false;
            while (!found) {
                inputLine = in.readLine();
                m = p.matcher(inputLine);
                if (m.find()) {
                    result = m.group();
                    found = true;
                }
            }

        } catch (IOException ioe) {
            System.out.println("The data cannot be accessed from the URL.");
            ioe.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException ioe2) {
            } // ignore this error
        }

        return result;
    }
}

Related

  1. getLocalNetWorkIp()
  2. getLocalV4Ip()
  3. getLocalV4IpList()
  4. getLongIp(byte[] buff)
  5. getLongIp(String ipString)
  6. getPublicIP()
  7. getPublicIP()
  8. getPublicIP()
  9. getPublicIP()