java - 为什么 InetAddress.getByName ("1.2") 是有效的 ip 地址?

标签 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.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.

编辑添加:如果 24 位部分让您感到困惑:

2 在 24 位中看起来像:00000000 00000000 00000010

然后将其映射到 IPv4 地址中右侧的 3 个八位字节为:.0.0.2

还有一个:正如 CoolBeans 在对您的问题的评论中提到的,InetAddressValidator来自 Apache commons 的文件就可以了。也就是说,如果您只想验证 IP 地址而不需要外部依赖,则可以使用 Regular Expressions to check IP addresses as well

关于java - 为什么 InetAddress.getByName ("1.2") 是有效的 ip 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9556978/

相关文章:

java - 当我使用 Content Assist 时 Eclipse 挂起

java - Hibernate:更新对象的最佳方式

java - 单元测试在 Debug模式下成功,但在正常运行时失败

java - 使用 Android 服务发送电子邮件

java - 方法调用不起作用?(Java NullPointerException)

java - Spring Stomp SimpUserRegistry 匿名用户

java - MySQL 表中的奇怪位值

java - 如何引用资源文件夹中的javafx fxml文件?

java - 使用 Java 高效地对数据库中的数据进行排序?

java - 如何在 Spring Data JPA 中获取最后一页作为默认值