java获取本机的外网IP地址

百度找java获取本机的外网IP地址都是以前的垃圾代码,别人页面都改了,怎么拿得到。

之前学过python的爬虫,拿外网ip简单就是通过 https://ip.chinaz.com/这个网站去得到。

百度习惯了,md !还百度了半天。

//代码拿去,有一说一效率有点低
/**
 * 得到本机的外网的外网IP地址 作为该局域网的区分标志
 * @return
 */
public static String getIp() {
    Document document = null;
    try {
        document = Jsoup.connect("https://ip.chinaz.com/").get();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Elements select = document.select("#leftinfo > div.IcpMain02.bor-t1s02 > div.WhoIpWrap.jspu > div.WhwtdWrap.bor-b1s.col-gray03 > span:nth-child(1)");
    String s = select.toString();
    String ip = s.substring(s.indexOf(">") + 1, s.lastIndexOf("<"));
    return ip;
}
//另一种方法,找到的有效:

 public static String getIP()  {
        String ip = "http://pv.sohu.com/cityjson?ie=utf-8";
        String inputLine = "";
        String read = "";
        String toIp="";
        try {
            URL url = new URL(ip);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }
            String ObjJson=inputLine.substring(inputLine.indexOf("=")+1,inputLine.length()-1);
//            System.out.println(ObjJson);
            JSONObject jsonObj= JSON.parseObject(ObjJson);
            toIp=jsonObj.getString("cip");
//            throw new Exception();
        } catch (Exception e) {
            toIp="";
        }
        return toIp;
    }


 /**
     * 根据域名获取ip地址
     */
    public static String getIfIP() {
        String toIp="";
        try{
            String pathName="baidu.com";//这里没有进行支持https协议的,可以自行进行切割字符串
            InetAddress address =InetAddress.getAllByName(pathName)[0];
            toIp=address.getHostAddress();
        }catch (Exception e){
            toIp="";
        }
        return toIp;
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值