gzyueqian
18529173453
首页 > 新闻中心 > > 正文

笨拙的实现IP地址归属查询

更新时间: 2007-05-31 14:16:52来源: 粤嵌教育浏览量:728


  公司要做个上网日志系统,系统中还得实现查询用户访问目标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());
}

}
}

免费预约试听课