java笔记---- 获取外网(公网)的ip地址

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;



public class MyTest {

    public static void main(String[] args) throws Exception {
        System.out.print(getV4IP());
    }

    public static String getV4IP() {
                String ip=null;
                try {
                    URL url = new URL("http://www.taobao.com/help/getip.php"); 
                    URLConnection URLconnection = url.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
                    int responseCode = httpConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        System.out.println("成功");   
                        InputStream in = httpConnection.getInputStream();
                        InputStreamReader isr = new InputStreamReader(in);
                        BufferedReader bufr = new BufferedReader(isr);
                        String str;
                        while ((str = bufr.readLine()) != null) {
                            ip=str;
                            System.out.println(str);
                        }
                        bufr.close();
                    } else {
                        System.err.println("失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                if(ip!=null){
                       
                   char[] chs=ip.toCharArray();
                   ip="";
                   for(int i=0;i<chs.length;i++){
                       if((chs[i]>=48&&chs[i]<=57)||chs[i]==46){
                           ip+=chs[i];
                       }
                   }
                }
                return ip;
        }





}

附加:

http://ip.360.cn/IPShare/info
http://myip.com.tw/
http://www.ip.cn

posted on 2019-03-11 10:35  Honey_Badger  阅读(645)  评论(0编辑  收藏  举报

导航

github