java教程

java获取ip地址 通过淘宝的IP地址库获取

位置:首页 > java教程 > java技巧,2019-03-11 20:49
java获取ip地址 通过淘宝的IP地址库获取获取外网(公网)的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;
        }

}

TAGS:java获取ip地址

猜你喜欢

NewHot