百度找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;
}