java – 为什么InetAddress.getByName(“1.2”)是有效的IP地址?

前端之家收集整理的这篇文章主要介绍了java – 为什么InetAddress.getByName(“1.2”)是有效的IP地址?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. public class InetAddresTest {
  2. public static void main(String ... agrs) {
  3. try {
  4. InetAddress inet = InetAddress.getByName("1.2");
  5. System.out.println("Good ip address");
  6. } catch (UnknownHostException e) {
  7. // TODO Auto-generated catch block
  8. e.printStackTrace();
  9. }
  10. }
  11. }

顺便说一下,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

猜你在找的Java相关文章