Skip to content

Instantly share code, notes, and snippets.

@KingSirLee
Created May 7, 2013 23:34
Show Gist options
  • Save KingSirLee/5537053 to your computer and use it in GitHub Desktop.
Save KingSirLee/5537053 to your computer and use it in GitHub Desktop.
根据主机来判断ip地址以及ip分类
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.Scanner;
public class MyIP {
public static void main(String[] args) throws Exception {
Scanner input=new Scanner(System.in);
System.out.println("输入要判断IP地址的主机名(网站):");
String host=input.next();
InetAddress address = InetAddress.getByName(host);
System.out.println("IP: " + address.getHostAddress());
switch (address.getAddress().length){
case 4:
System.out.println("根据byte数组长度判断这个IP地址是IPv4地址!");
break;
case 16:
System.out.println("根据byte数组长度判断这个IP地址是IPv6地址!");
break;
}
if (address instanceof Inet4Address){
System.out.println("使用instanceof判断这个IP地址是IPv4地址!");
}
if (address instanceof Inet6Address){
System.out.println("使用instanceof判断这个IP地址是IPv6地址!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment