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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一下,InetAddress产生的ip地址回复为"1.0.0.2".我无法从InetAddress的javadoc中找到合理的答案.你能解释一下这种行为吗?
从的Javadoc (链接在"IP地址的文本表示" 的Javadoc的InetAddress):
当提供两部分地址时,最后一部分被解释为24位数量并放在网络地址的最右边三个字节中.这使得两部分地址格式便于将A类网络地址指定为net.host.
编辑添加:如果24bit部分让您感到困惑:
2 在24位看起来像: 00000000 00000000 00000010
然后将其映射到IPv4地址中右边的3个八位字节,如下所示: .0.0.2
还有一个:正如CoolBeans在你的问题的评论中提到的那样,来自Apache commons 的InetAddressValidator可以解决这个问题.话虽这么说,如果你只想验证IP地址而不是外部依赖,你可以使用正则表达式来检查IP地址