笨拙的實現IP地址歸屬查詢
更新時間: 2007-05-31 14:16:52來源: 粵嵌教育瀏覽量:717
公司要做個上網日志系統,系統中還得實現查詢用戶訪問目標ip歸屬查詢,頂,這個如果本地實現實在不簡單,大問題就是誰去維護這個ip庫啊?所以出此下策,大家看了不要罵我啊,呵呵。代碼很簡單,希望對大家有用。
public class IpAddrSearch {
public IpAddrSearch() {
}
/*寄主服務器,我選擇了兩個更新比較及時,而且速度比較快的地方*/
private static String urlhead = "http://emuch.net/ip.php?iptext="; //http://emuch.net/ip.php?iptext=
private static String urlhead1 = "http://www.njci.net/ip/ip.aspx?ip="; //http://www.njci.net/ip/ip.aspx=
public static String getRealAddr_emuch(String ipaddr) {
String urlstr = urlhead + ipaddr;
URL url = null;
InputStream is = null;
String indexstr = null;
String readdr = null;
byte rebuf[] = new byte[4096];
int index1;
try {
url = new URL(urlstr);/*模擬http去訪問*/
} catch (MalformedURLException ex) {
ex.printStackTrace();
return null;
}
URLConnection uc = null;
try {
uc = url.openConnection();
} catch (IOException ex1) {
ex1.printStackTrace();
return null;
}
try {
is = uc.getInputStream();/*獲取http文本*/
} catch (IOException ex2) {
ex2.printStackTrace();
return null;
}
try {
is = uc.getInputStream();
{/*笨拙的分析html標記*/
if (is.read(rebuf) == -1) return null;
readdr = new String(rebuf, "gb2312");
indexstr = ipaddr + "#";
index1 = readdr.indexOf(indexstr);
if (index1 != -1) {
readdr = readdr.substring(index1 + indexstr.length(),
index1 + indexstr.length() + 36);
index1 = readdr.indexOf("\n");
if (index1 != -1)
readdr = readdr.substring(0, index1 - 1);
readdr = readdr.replaceAll("EMUCH.NET", "");
}else
readdr = null;
//is.close();
}
} catch (IOException ex2) {
ex2.printStackTrace();
return null;
}
readdr = readdr.trim();
if (readdr == "") {
readdr = null;
}
return readdr;
}
public static String getRealAddr_njci(String ipaddr) {
String urlstr = urlhead1 + ipaddr;
URL url = null;
InputStream is = null;
String re = null;
String readdr = null;
byte rebuf[] = new byte[1024];
try {
url = new URL(urlstr);
} catch (MalformedURLException ex) {
ex.printStackTrace();
return null;
}
URLConnection uc = null;
try {
uc = url.openConnection();
} catch (IOException ex1) {
ex1.printStackTrace();
return null;
}
try {
is = uc.getInputStream();
is.read(rebuf);
readdr = new String(rebuf, "UTF-8");
} catch (IOException ex2) {
ex2.printStackTrace();
return null;
}
readdr = readdr.trim();
if (readdr == "") {
readdr = null;
}
return readdr;
}
private static String getStr(String str) {
try {
String temp_p = str;
byte[] temp_t = temp_p.getBytes("8859_1");
String temp = new String(temp_t, "GB2312");
return temp;
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
byte b4[] = {(byte) 202, 96, 1, 24};
int i = 0;
InetAddress ia = null;
/*測試查詢一個C的地址歸屬*/
for (i = 1; i<254; i++)
{
b4[2] = (byte)i;
try {
ia = InetAddress.getByAddress(b4);
} catch (UnknownHostException ex) {
}
System.out.println(IpAddrSearch.getRealAddr_emuch(ia.getHostAddress()) + ":"+ia.getHostAddress());
}
}
}