java获取服务器真实外网IP

来源:互联网 发布:淘宝开店上传坐套教程 编辑:程序博客网 时间:2024/05/22 00:11
package com.xiaoma.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.URL;import java.net.URLConnection;import org.jsoup.Connection;import org.jsoup.Jsoup;import org.jsoup.nodes.Element;import org.junit.Test;public class GetPublicIP {public GetPublicIP(){}public static String getPublicIp(){//此方法需要引入Jsoup.jar包//您的IP是:[218.18.123.160] 来自:广东省深圳市 电信String ip="";org.jsoup.nodes.Document doc = null;Connection con = null; con = Jsoup.connect("http://20140507.ip138.com/ic.asp").timeout(10000);   try {doc = con.get();//获取包含本机ip的文本串org.jsoup.select.Elements els = doc.body().select("center");for(Element el:els){ip=el.text();}//ip = ip.replaceAll("[^0-9.]", "");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return ip;}  return ip;}public static String getPublicIp2() throws IOException{//218.18.123.160String ip="";URL url = new URL("http://20140507.ip138.com/ic.asp");  URLConnection conn = url.openConnection();  conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15");  conn.setRequestProperty("Content-Type", "text/html");  conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");  InputStream is = conn.getInputStream();  BufferedReader br = new BufferedReader(new InputStreamReader(is, "GB2312"));  String line = null;  while ((line = br.readLine()) != null) {   if (line.contains("您的IP是")) {    // System.out.println(line);    int start = line.indexOf('[') + 1;    int end = line.indexOf(']');    ip = line.substring(start, end);   }  }  br.close();  return ip;}@Testpublic void testsss() throws IOException{System.out.println(GetPublicIP.getPublicIp());System.out.println(GetPublicIP.getPublicIp2());}}

0 0