利用Java socket 实现根据IP地址查询该IP相关的注册信息。
源代码直接下载:java_whois.zip
相关的两个类WhoisBean.java 和WhoisQuery.java 代码实现如下:
Java代码
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
*
* @author Michael sun
*/
public class WhoisQuery {
/**
*
* @param ip
*/
private void queryIpInfo(String ip) {
Map<String, String> map = new LinkedHashMap<String, String>();
try {
WhoisBean bean = new WhoisBean();
bean.setTimeout(0);
// bean.setServer("whois.apnic.net");
bean.setServer("whois.ripe.net");
bean.queryInfoByIp(ip);
List<String> infoList = bean.getInfoList();
String value = "";
String key = "";
for (String infoTmp : infoList) {
String[] arr = infoTmp.split(":[ ]*");
if (arr.length > 1) {
key = arr[0];
value = arr[1];
} else {
value = arr[0].trim();
}
if (null == map.get(key)) {
map.put(key, "");
}
value = map.get(key) + value;
map.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
/**
* @param args
*/
public static void main(String[] args) {
String ip = "129.42.58.216";// "163.1.13.189";
WhoisQuery query = new WhoisQuery();
query.queryIpInfo(ip);
}
}
Java代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* WhoisBean
* @author Michael sun
*/
public class WhoisBean {
/**
* server address
*/
private String server = "";
/**
* port
*/
private int port = 43;
/**
* timeout/minute
*/
private int timeout = 0;
/**
* infoList
*/
private List<String> infoList = new ArrayList<String>();
/**
* @param ip
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void queryInfoByIp(String ip) throws Exception {
Socket theSocket = null;
BufferedReader br = null;
PrintStream ps = null;
int qryCount = 0;
while (qryCount < 5) {
qryCount++;
try {
theSocket = new Socket(server, port);
theSocket.setSoTimeout(timeout * 1000);
ps = new PrintStream(theSocket.getOutputStream());
ps.println(ip);
br = new BufferedReader(new InputStreamReader(theSocket
.getInputStream()));
infoList.add("ip:" + ip);
String readLine = "";
int i = 0;
System.out.println("Whois query read start.... ");
while ((readLine = br.readLine()) != null) {
System.out.println("***" + readLine);
if (readLine.length() > 0 && readLine.charAt(0) != '%') {
infoList.add(readLine);
i++;
// 默认读取100行数据
if (i > 100 || readLine.startsWith("source")) {
break;
}
}
}
考试大温馨提示:本内容来源于网络,仅代表作者个人观点,与本站立场无关,仅供您学习交流使用。其中可能有部分文章经过多次转载而造成文章内容缺失、错误或文章作者不详等问题,请您谅解。如有侵犯您的权利,请联系我们,本站会立即予以处理。
编辑推荐:
统计你写的java代码行数
JavaTimer和TimerTask详解
8个改善Java遗留系统的技巧