public class InetAddresTest { public static void main(String ... agrs) { try { InetAddress inet = InetAddress.getByName("1.2"); System.out.println("Good ip address"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
顺便说一下,InetAddress产生的ip地址回复为“1.0.0.2”.我无法从InetAddress的javadoc中找到合理的答案.你能解释一下这种行为吗?
解决方法
从
Javadoc(在
Javadoc for InetAddress中以“IP地址的文本表示”链接):
When a two part address is supplied,the last part is interpreted as a 24-bit quantity and placed in the right most three bytes of the network address. This makes the two part address format convenient for specifying Class A network addresses as net.host.
编辑添加:如果24bit部分让您感到困惑:
24位中的2将看起来像:00000000 00000000 00000010
然后将其映射到IPv4地址中右边的3个八位字节:.0.0.2
另外一点:正如CoolBeans在对你的问题的评论中提到的那样,来自Apache commons的InetAddressValidator就可以解决问题了.话虽这么说,如果你只想验证IP地址而不是外部依赖,你可以使用Regular Expressions to check IP addresses as well