获取本机外网IP的工具类

ExternalIpAddressFetcher.java

package com.tyust.common;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;  

/**
 * 获取本机外网IP地址
 * 思想是访问网站http://checkip.dyndns.org/,得到返回的文本后解析出本机在外网的IP地址
 * @author Administrator
 *
 */
public class ExternalIpAddressFetcher {
    // 外网IP提供者的网址
    private String externalIpProviderUrl;  

    // 本机外网IP地址
    private String myExternalIpAddress;  

    public ExternalIpAddressFetcher(String externalIpProviderUrl) {
        this.externalIpProviderUrl = externalIpProviderUrl;  

        String returnedhtml = fetchExternalIpProviderHTML(externalIpProviderUrl);  

        parse(returnedhtml);
    }  

    /**
     * 从外网提供者处获得包含本机外网地址的字符串
     * 从http://checkip.dyndns.org返回的字符串如下
     * <html><head><title>Current IP Check</title></head><body>Current IP Address: 123.147.226.222</body></html>
     * @param externalIpProviderUrl
     * @return
     */
    private String fetchExternalIpProviderHTML(String externalIpProviderUrl) {
        // 输入流
        InputStream in = null;  

        // 到外网提供者的Http连接
        HttpURLConnection httpConn = null;  

        try {
            // 打开连接
            URL url = new URL(externalIpProviderUrl);
            httpConn = (HttpURLConnection) url.openConnection();  

            // 连接设置
            HttpURLConnection.setFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");  

            // 获取连接的输入流
            in = httpConn.getInputStream();
            byte[] bytes=new byte[1024];// 此大小可根据实际情况调整  

            // 读取到数组中
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                   && (numRead=in.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }  

            // 将字节转化为为UTF-8的字符串
            String receivedString=new String(bytes,"UTF-8");  

            // 返回
            return receivedString;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                httpConn.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }  

        // 出现异常则返回空
        return null;
    }  

    /**
     * 使用正则表达式解析返回的HTML文本,得到本机外网地址
     * @param html
     */
    private void parse(String html){
        Pattern pattern=Pattern.compile("(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})", Pattern.CASE_INSENSITIVE);
        Matcher matcher=pattern.matcher(html);
        while(matcher.find()){
            myExternalIpAddress=matcher.group(0);
        }
    }      

    /**
     * 得到本机外网地址,得不到则为空
     * @return
     */
    public String getMyExternalIpAddress() {
        return myExternalIpAddress;
    }  

    public static void main(String[] args){
        ExternalIpAddressFetcher fetcher=new ExternalIpAddressFetcher("http://checkip.dyndns.org/");  

        System.out.println(fetcher.getMyExternalIpAddress());
    }
}  

也可以直接访问网站:

原文地址:https://www.cnblogs.com/qlqwjy/p/8424688.html

时间: 2024-07-28 15:17:04

获取本机外网IP的工具类的相关文章

php 通过ip获取所在城市地址信息 获取计算机外网ip

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-

用Linux命令行获取本机外网IP地址

用Linux命令行获取本机外网IP地址 $ curl ifconfig.me$ curl icanhazip.com$ curl ident.me$ curl ipecho.net/plain$ curl whatismyip.akamai.com$ curl tnx.nl/ip$ curl myip.dnsomatic.com$ curl ip.appspot.com$ curl -s checkip.dyndns.org | sed 's/.*IP Address: \([0-9\.]*\)

获取本机外网ip和内网ip

获取本机外网ip 1 //获取本机的公网IP 2 public static string GetIP() 3 { 4 string tempip = ""; 5 try 6 { 7 WebRequest request = WebRequest.Create("http://ip.qq.com/"); 8 request.Timeout = 10000; 9 WebResponse response = request.GetResponse(); 10 Stre

Linux终端中获取本机外网 IP 的方法

在终端中输入 curl ipinfo.io 或者 curl ifconfig.me 即可通过IP地址检测网站提供的api获得取本机的外网IP,或者以 JSON 格式返回全部结果.

获取本机外网ip地址

package com.ning; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class Listip { public static void main(String[] args) throws Exception { System.out.println("本机的外网IP是:" //+ Listip.getWebIp("http

Python获取本机外网IP

1. 打开https://www.baidu.com/ 2. 输入ip, 进行搜索, 获取url http://cn.bing.com/search?q=ip&go=%E6%8F%90%E4%BA%A4&qs=n&form=QBLH&pq=ip&sc=8-2&sp=-1&sk=&cvid=14b93b305cdc4183875411c3d9edf938 3. 查找url返回结果 编写python匹配正则表达式 4. Python完整代码 1

linux 通过命令行获取本机外网IP

curl ifconfig.me curl icanhazip.com curl ident.me curl whatismyip.akamai.com curl tnx.nl/ip curl myip.dnsomatic.com 版权声明:本文为博主原创文章,未经博主允许不得转载.

java 获取公网(外网IP)很实用!

package com.lovo.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PublicInterIp { /** * @param args * @throws Exception */ public S

Windows Azure 配置实现虚拟机外网IP绑定(云服务)

我们上一篇介绍了如何对已存在的虚拟网络的外网IP做绑定,今天主要介绍配置实现虚拟机外网绑定,两者区别在于一个已存在,一个不存在,如果不存在的话,我们需要新建一个云服务,同时对新建的云服务做标记,标记后,可创建对应得虚拟机来完成外网IP绑定,具体见下:首先注意配置保留虚拟机外网IP需要注意以下事项 一. 操作前的注意事项: 1. 如果虚拟机要使用虚拟网络,只能在Regional Vnet中使用ReservedIP,已经有部署的基于地缘组的虚拟网络无法直接转换为Regional Vnet 2. 这个