加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:57:38 所属栏目:Java 来源:网络整理
导读: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.
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读