java获取本地外网ip地址

3 篇文章 0 订阅
1 篇文章 0 订阅

获取本机外网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地址

 /**
     * 根据域名获取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;
    }

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值