Java IP Address Get getPublicIpViaHttp()

Here you can find the source of getPublicIpViaHttp()

Description

This will retrieve your IP address via an HTTP server.

License

Apache License

Return

the public IP address if found, or null if it didn't find it

Declaration

@Deprecated
public static String getPublicIpViaHttp() 

Method Source Code


//package com.java2s;
/*/*w w  w .j a v  a 2  s  .com*/
 * Copyright 2015 dorkbox, llc
 *
 * 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.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

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

public class Main {
    /**
     * This will retrieve your IP address via an HTTP server.
     * <p/>
     * <b>NOTE: Use DnsClient.getPublicIp() instead. It's much faster and more reliable as it uses DNS.</b>
     *
     * @return the public IP address if found, or null if it didn't find it
     */
    @Deprecated
    public static String getPublicIpViaHttp() {
        // method 1: use DNS servers
        // dig +short myip.opendns.com @resolver1.opendns.com

        // method 2: use public http servers
        // @formatter:off
        final String websites[] = { "http://ip.dorkbox.com/", "http://ip.javalauncher.com/",
                "http://checkip.dyndns.com/", "http://checkip.dyn.com/", "http://curlmyip.com/", "http://tnx.nl/ip",
                "http://ipecho.net/plain", "http://icanhazip.com/", "http://ip.appspot.com/", };
        // @formatter:on

        // loop, since they won't always work.
        for (int i = 0; i < websites.length; i++) {
            try {
                URL autoIP = new URL(websites[i]);
                BufferedReader in = new BufferedReader(new InputStreamReader(autoIP.openStream()));
                String response = in.readLine().trim();
                in.close();

                Pattern pattern = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b");
                Matcher matcher = pattern.matcher(response);
                if (matcher.find()) {
                    return matcher.group().trim();
                }
            } catch (Exception ignored) {
            }
        }

        return null;
    }
}

Related

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