Java 查询URL对应IP地址

/**
 * @ClassName TestSocket1
 * @Version 1.0
 * @Date 2014-9-26 上午10:19:36
 */
public class TestSocket1 {

	public static void main(String[] args) throws UnknownHostException {

		String str = "";
		Scanner scanner = new Scanner(System.in);

		while (true) {
			System.out.println("请输入需要查询的URL:");
			str = scanner.nextLine().trim();
			if (str.equalsIgnoreCase("exit")) {
				System.out.println("程序退出");
				break;
			} else if (str.length() == 0) {
				System.out.println("本机IP " + getLocalHost(str));
			} else {
				System.out.println(Arrays.toString(getWebHost(str).toArray()));
			}
		}
	}

	private static String getLocalHost(String url) throws UnknownHostException {
		return InetAddress.getLocalHost().toString();
	}

	private static List<String> getWebHost(String url)
			throws UnknownHostException {

		List<String> res = new LinkedList<String>();
		InetAddress[] address = InetAddress.getAllByName(url);
		for (InetAddress inetaddress : address) {
			res.add(inetaddress.getHostAddress());
		}
		return res;
	}
}

  

posted on 2014-09-26 10:52  小沫9  阅读(910)  评论(0编辑  收藏  举报