java将域名解析为IP地址

来源:互联网 发布:js访问器属性有什么用 编辑:程序博客网 时间:2024/05/18 17:01
熟悉InetAddress类:InetAddress类主要是用来得到所指定的网络地址,InetAddress类没有直接显式的构造函数。要生成一个InetAddress对象,必须运用一个可用的工厂方法。工厂方法(factory method)仅是一个类中的静态方法返回一个该类实例的约定。这是在一个带有各种参数列表的重载构造函数中完成的,当持有惟一方法名时可使结果更清晰。

InetAddress有三个方法可以用来创建InetAddress的实例

1.static InetAddress getLocalHost( ) throws UnknownHostException

2.static InetAddress getByName(String hostName) throws UnknownHostException

3.static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException

InetAddress类的非静态方法

   boolean equals(Object other)
如果对象具有和other相同的Internet地址则返回true。
byte[ ] getAddress( )
返回此InetAddress对象的原始 IP 地址。
String getHostAddress( )
返回与InetAddress对象相关的主机地址的字符串。
String getHostName( )
返回与InetAddress对象相关的主机名的字符串。
int hashCode( )
返回调用对象的散列码。
boolean isMulticastAddress( )
如果Internet地址是一个多播地址则返回true;否则返回false。 
String toString( )
返回主机名字符串和IP地址。

下面我们写一个程序来解析域名:

package com.ip;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.Scanner;public class IP {    public static void main(String[]args)    {        try {            System.out.print("请输入要解析的域名:");            Scanner in=new Scanner(System.in);            String domainname=in.nextLine();//输入要解析的域名            System.out.println("使用InetAddress类的方法获取网站"+domainname+"的IP地址...");                System.out.println("总共ip个数:"                        + InetAddress.getAllByName(domainname).length);//获取接续出来的ip的个数                InetAddress[] inetadd = InetAddress.getAllByName(domainname);                //遍历所有的ip并输出                for (int i = 0; i < inetadd.length; i++) {                    System.out.println("第" + (i + 1) + "个ip:" + inetadd[i]);                }        } catch (UnknownHostException e) {            System.out.println("获取网站www.csdn.net的IP地址失败!没有对应的IP!");        }    }}

结果:


0 0
原创粉丝点击