通过dns解析获取域名的ip地址

星期二, 2012-12-04 | Author: Lee | JAVA-and-J2EE | 4,423 views

可以通过域名获取域名解析的ip地址,java版本,通过java的本地dns解析,如果本地设置了host的解析地址将会和真实ip地址有出入:

获取www.qq.com的ip地址如下:
ipv4:222.73.78.166
ipv4:222.73.78.171
ipv4:222.73.78.181
ipv4:101.226.42.62
ipv4:101.226.49.101
ipv4:115.236.139.153
ipv4:180.153.210.43

code如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.i5a6.leeyz.ip;
 
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class TestGetIp {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, List<String>> map = getHostIp("www.qq.com");
		if (map == null) {
			System.out.println("local dns is error!");
			return;
		}
		if (map.containsKey("ipv4")) {
			for (String ip : map.get("ipv4")) {
				System.out.println("ipv4:" + ip);
			}
		}
		if (map.containsKey("ipv6")) {
			for (String ip : map.get("ipv6")) {
				System.out.println("ipv6:" + ip);
			}
		}
 
	}
 
	//java 通过dns解析获取域名的主机ip地址
	public static Map<String, List<String>> getHostIp(String host) {
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		try {
			InetAddress[] ipArray = InetAddress.getAllByName(host);
			for (InetAddress ip : ipArray) {
				if (ip instanceof Inet4Address) {
					if (!(map.containsKey("ipv4"))) {
						List<String> list = new ArrayList<String>();
						map.put("ipv4", list);
					}
					map.get("ipv4").add(ip.getHostAddress());
				} else if (ip instanceof Inet6Address) {
					if (!(map.containsKey("ipv6"))) {
						List<String> list = new ArrayList<String>();
						map.put("ipv6", list);
					}
					map.get("ipv6").add(ip.getHostAddress());
				}
			}
		} catch (Exception e) {
			return null;
		}
		return map;
	}
 
}

Tags: ,

文章作者: Lee

本文地址: http://blog.i5a6.com/1069.html

除非注明,I5A6文章均为原创,转载请以链接形式标明本文地址

还没有评论呢。

留下评论

Rss

Search

文章分类

Meta