Created
July 11, 2013 23:40
-
-
Save Chinaxiang/5980267 to your computer and use it in GitHub Desktop.
java网络编程,InetAddress类实现IP地址的类型判断。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.Inet4Address; | |
import java.net.Inet6Address; | |
import java.net.InetAddress; | |
import java.net.UnknownHostException; | |
public class IPTest { | |
public static void main(String[] args) { | |
InetAddress address; | |
try { | |
//根据网址域名查出地址 | |
//address=InetAddress.getLocalHost(); | |
address=InetAddress.getByName("www.baidu.com"); | |
System.out.println("IP地址:"+address); | |
String add1=address.getHostAddress();//61.135.169.125 | |
String add2=address.getHostName();//www.baidu.com | |
byte[] addr=address.getAddress(); | |
System.out.println(add1); | |
System.out.println(add2); | |
int k=addr[0]; | |
if(k<0){ | |
k=k+256; | |
} | |
if(address instanceof Inet4Address){ | |
System.out.println("当前地址类型为IPv4地址!"); | |
if(k>=1&&k<=127){ | |
System.out.println("该地址是A类地址"); | |
}else if(k>=128&&k<=191){ | |
System.out.println("该地址是B类地址"); | |
}else if(k>=192&&k<=223){ | |
System.out.println("该地址是C类地址"); | |
}else if(k>=224&&k<=239){ | |
System.out.println("该地址是D类地址"); | |
}else if(k>=234&&k<=254){ | |
System.out.println("该地址是E类地址"); | |
}else{ | |
System.out.println("该地址非法"); | |
} | |
}else if(address instanceof Inet6Address){ | |
System.out.println("根据地址类型判断,该地址是IPv6地址!"); | |
}else{ | |
System.out.println("该地址不是IPv6,也不是IPv4"); | |
} | |
System.out.println(addr[0]); | |
System.out.println(addr[1]); | |
System.out.println(addr[2]); | |
System.out.println(addr[3]); | |
/*address = InetAddress.getLocalHost();//获取当前IP地址 | |
System.out.println(address);*/ | |
} catch (UnknownHostException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment