InetAddress類及Inet4Address/Inet6Address的使用方法
InetAddress類及Inet4Address/Inet6Address的使用方法
了解域名系統(DNS)原理,掌握InetAddress類及Inet4Address/Inet6Address的使用方法。
編寫一個可重用的域名解析程式子產品,使之能夠将使用者輸入的域名解析為IP位址。
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
public class GetIP {
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);
InetAddress[] inetaddress = InetAddress.getAllByName(domainname);
for (int i = 0; i < inetaddress.length; i++) {
System.out.println("第" + (i + 1) + "個IP:" + inetaddress[i].getHostAddress());
String add = inetaddress[i].getHostAddress();
int length=add.length();
if(length <= 16)
System.out.println("根據byte數組長度判斷此IP位址是IPv4位址!");
if(length > 16)
System.out.println("根據byte數組長度判斷此IP位址是IPv6位址!");
}
} catch (UnknownHostException e) {
System.out.println("擷取失敗,沒有對應的IP!");
}
}
}