动态检测出口IP,精确到市级

本文介绍了一种利用Java库Jsoup从网页抓取公共IP地址的方法。通过两个不同的网站,实现了自动化的IP地址和地理位置信息获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.IOException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
public class IpCheck {
public String getPublicIP1() {
StringBuffer res = new StringBuffer("");
final String siteAddress = "http://ip.8558.org/";
org.jsoup.nodes.Document doc = null;
Connection con = null;
con = Jsoup.connect(siteAddress).timeout(10000);
try {
doc = con.get();
// 取得所有的tr标签
org.jsoup.select.Elements elsTr = doc.body().select("tr");
if (elsTr.size() >= 3) {
// 取得ip和isp所在的最底层标签
org.jsoup.select.Elements els = elsTr.get(2).select("font");
if (els.size() == 2) {
res.append(els.get(0).text());
res.append("(");
res.append(els.get(1).text());
res.append(")");
}
} 
} catch (IOException e) {
e.printStackTrace();
}
return res.toString();
}
public String getPublicIP2(){
StringBuffer res = new StringBuffer("") ;
String siteAddress = "http://20140507.ip138.com/ic.asp" ;
org.jsoup.nodes.Document doc = null ;
Connection con = null ;
con = Jsoup.connect(siteAddress).timeout(10000);
try {
doc = con.get();

org.jsoup.select.Elements els = doc.body().select("center");

//您的IP是:[119.40.37.65] 来自:北京市
String text = els.text() ;
int start = text.indexOf("[");
int end = text.indexOf("]");
res.append(text.substring(start + 1, end));
res.append("(");
int pos = text.lastIndexOf(":");
res.append(text.substring(pos+1));
res.append(")");
} catch (IOException e) {
e.printStackTrace();
}
return res.toString() ;
}
public String testOutIP(){

return 0 == getPublicIP1().length() ? getPublicIP2() : getPublicIP1() ;
}

public static void main(String[] args){
IpCheck ic = new IpCheck();

System.out.println("["+ic.testOutIP()+"]");
System.out.println("["+ic.getPublicIP2()+"]");
}
}


需要用到的Jsoup   jar包自行下载。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值