在 Java 中检查有效的 IPv4 地址

发布于 2024-12-06 17:49:58 字数 710 浏览 0 评论 0原文

我正在使用 sun.net.util.IPAddressUtil 包来检查字符串是否包含有效的 IPv4 和 IPv6 地址。

代码片段是:-

String ipv4addr="200";

    if(IPAddressUtil.isIPv4LiteralAddress(ipv4addr))
    {
        System.out.println("valid ipv4 address");
    }
    else
    {
        System.out.println("not valid");

    }

但是对于 200 和 300 等地址,它仍然说它是有效的 IPv4 地址,但事实并非如此。 当我使用相同的包并使用 :- 检查 IPV6 地址时,

String ipv6addr="200";

    if(IPAddressUtil.isIPv6LiteralAddress(ipv6addr))
    {
        System.out.println("valid ipv6 address");
    }
    else
    {
        System.out.println("not valid");

    }

我得到了正确的结果。但是,IPv4 似乎不起作用,或者可能是我使用不当。请指导我。我不想使用正则表达式进行 IPv4 验证...

I am using the sun.net.util.IPAddressUtil package to check whether the string contains a valid IPv4 and IPv6 address or not.

Code Snippet is:-

String ipv4addr="200";

    if(IPAddressUtil.isIPv4LiteralAddress(ipv4addr))
    {
        System.out.println("valid ipv4 address");
    }
    else
    {
        System.out.println("not valid");

    }

But for addresses such as 200 and 300 it is still saying it is a valid IPv4 address, which it isn't.
When I used the same package and checked for IPV6 address using :-

String ipv6addr="200";

    if(IPAddressUtil.isIPv6LiteralAddress(ipv6addr))
    {
        System.out.println("valid ipv6 address");
    }
    else
    {
        System.out.println("not valid");

    }

I get the correct result. However, IPv4 does not seem to be working or may be I am using it incorrectly. Please guide me. I don't want to use regex for IPv4 validation...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小霸王臭丫头 2024-12-13 17:49:59

使用内部“sun”打包类不是一个好主意,我会尝试使用 Apache 的 Validator

http://commons .apache.org/validator/

具有 IP 地址验证功能。

It's not a good idea to use internal "sun" packaged classes, I'd try using Apache's Validator

http://commons.apache.org/validator/

which has IP Address validation.

余罪 2024-12-13 17:49:59

如果要验证字符串是否是有效的 IP 地址表示形式,请参考 org.apache.http.conn.util.InetAddressUtils 使用这些正则表达式:

IPV4_PATTERN = Pattern.compile(
    "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
IPV6_STD_PATTERN = Pattern.compile(
    "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile(
    "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");

If you want to validate if a string is valid IP address representation, the source code of org.apache.http.conn.util.InetAddressUtils uses these regular expressions:

IPV4_PATTERN = Pattern.compile(
    "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
IPV6_STD_PATTERN = Pattern.compile(
    "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile(
    "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");
云仙小弟 2024-12-13 17:49:59

该字符串是一种 IPv4 字符串格式,最初由 BSD Unix 中的 aton_inet 实用程序引入,并且在各种 Unix 和 Linux 风格以及其他地方一直沿用至今。

https://linux.die.net/man/3/inet_aton

IPAddress Java 库 将进行验证,可以配置为支持或不支持 aton_inet 格式。 javadoc 可在链接中找到。免责声明:我是项目经理。

验证地址是否有效,允许 inet_aton 样式:

    String str = "200";
    IPAddressString addrString = new IPAddressString(str);
    try {
         IPAddress addr = addrString.toAddress();
         System.out.println("valid address: " + addr.toCanonicalString());
    } catch(IPAddressStringException e) {
        System.out.println(e.getMessage());
    }

输出:

有效地址:0.0.0.200

验证地址是否有效,不允许 inet_aton 样式:

    IPAddressStringParameters parameters = new       
      IPAddressStringParameters.Builder().allow_inet_aton(false).toParams();
    addrString = new IPAddressString(str, parameters);
    try {
         IPAddress addr = addrString.toAddress();
         System.out.println("valid address: " + addr.toCanonicalString());
    } catch(IPAddressStringException e) {
        System.out.println(e.getMessage());
    }

输出:

200 IP 地址错误:选项不允许少于四个段的 IPv4 地址

That string is an IPv4 string format that was originally introduced by the aton_inet utility in BSD Unix and has persisted until this day in the various Unix and Linux flavours and elsewhere.

https://linux.die.net/man/3/inet_aton

The IPAddress Java library will do validation that can be configured to support aton_inet formats or not. The javadoc is available at the link. Disclaimer: I am the project manager.

Verify if an address is valid, allow inet_aton style:

    String str = "200";
    IPAddressString addrString = new IPAddressString(str);
    try {
         IPAddress addr = addrString.toAddress();
         System.out.println("valid address: " + addr.toCanonicalString());
    } catch(IPAddressStringException e) {
        System.out.println(e.getMessage());
    }

Output:

valid address: 0.0.0.200

Verify if an address is valid, do not allow inet_aton style:

    IPAddressStringParameters parameters = new       
      IPAddressStringParameters.Builder().allow_inet_aton(false).toParams();
    addrString = new IPAddressString(str, parameters);
    try {
         IPAddress addr = addrString.toAddress();
         System.out.println("valid address: " + addr.toCanonicalString());
    } catch(IPAddressStringException e) {
        System.out.println(e.getMessage());
    }

Output:

200 IP Address error: options do not allow IPv4 address with less than four segments

伏妖词 2024-12-13 17:49:59

经过一番小研究后,我最终得到了这样的结果,

    public static boolean isValidIP4Address(String ipAddress) {
        if (ipAddress.matches("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$")) {
            String[] groups = ipAddress.split("\\.");

            for (int i = 0; i <= 3; i++) {
                String segment = groups[i];
                if (segment == null || segment.length() <= 0) {
                    return false;
                }

                int value = 0;
                try {
                    value = Integer.parseInt(segment);
                } catch (NumberFormatException e) {
                    return false;
                }
                if (value > 255) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

这对于简单的检查来说是很好的。

After a small research I ended up with something like this

    public static boolean isValidIP4Address(String ipAddress) {
        if (ipAddress.matches("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$")) {
            String[] groups = ipAddress.split("\\.");

            for (int i = 0; i <= 3; i++) {
                String segment = groups[i];
                if (segment == null || segment.length() <= 0) {
                    return false;
                }

                int value = 0;
                try {
                    value = Integer.parseInt(segment);
                } catch (NumberFormatException e) {
                    return false;
                }
                if (value > 255) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

which was fine for simple checks.

眼趣 2024-12-13 17:49:58

您获得“有效”结果是有原因的:200 是一个有效的 IPv4 地址。

对于计算机来说,IPv4 地址只是一个 32 位数字。这些点完全是为了我们的方便,因为我们人类不擅长记住大而精确的数字。但他们不必在那里;关于如何解析地址有一些规则,具体取决于地址有多少部分。

当地址由一个数字组成时,它被视为 32 位数字,每个字节是该数字的 8 位。如果您将“200”解析为IP地址,它将相当于0.0.0.200。同样,"2130706433" 相当于 127.0.0.1。

当地址由两部分组成时,也有一些标准,例如 0.200(第一部分是第一个字节,第二部分是代表其他 3 个字节的 24 位数字),甚至 0.0.200(前两个数字是字节,最后一部分是 16 位,占用另外 2 个字节)。 “不寻常”的格式是 IP 地址分类时代的遗留物,但几乎所有必须解析地址的软件都会理解它们。 (如果您弹出浏览器并转到 http://1249739112* 甚至 http://74.125.33128* ,例如,Google 的主页将会出现。)

* 请参阅可点击链接的注释。谢谢“链接验证器”。 :P

请参阅 http://download。 oracle.com/javase/6/docs/api/java/net/Inet4Address.htmlhttp://www.perlmonks.org/?node_id=221512,或 http://en.wikipedia.org/wiki/IPv4#Address_representations,了解更多详细信息。

Java 也理解这些格式(.net 以及任何像样的操作系统也是如此),并正确解析地址,无论它包含 1、2、3 还是 4 个部分。

如果您想检查一个可能的地址实际上看起来像“xxx.xxx.xxx.xxx”,那么您可能需要使用模式或使用将 32 位数字视为无效地址(即使它们有效)。不过,我不会打扰 - 如果您使用提供的查找功能,您可以接受任何标准格式的地址并且它会起作用。

(所有这些混乱都随着 IPv6 的改变而改变;有更严格的格式,你不能只输入一些 36 位数字并期望它能够工作。但是该平台仍然知道如何解析地址,你应该信任它这样做。)

There's a reason you're getting a "valid" result: 200 is a valid IPv4 address.

See, to the computer, an IPv4 address is just a 32-bit number. The dots are entirely for our convenience, because we humans suck at memorizing big precise numbers. But they don't have to be there; there are rules about how an address gets parsed depending on how many parts it has.

When an address consists of one number, it's considered a 32-bit number, and each byte is 8 bits of that number. If you were to parse "200" as an IP address, it would be equivalent to 0.0.0.200. Likewise, "2130706433" would be equivalent to 127.0.0.1.

There are also standards for when an address has two parts like 0.200 (first part is the first byte, and the second part is a 24-bit number representing the other 3 bytes), and even 0.0.200 (first two numbers are bytes, the last part is 16 bits and takes up the other 2 bytes). The "unusual" formats are leftovers from the days of IP address classes, but almost all software that has to parse addresses will understand them. (If you pop open your browser and go to http://1249739112* or even http://74.125.33128*, for example, Google's home page will come up.)

* See the comments for clickable links. Thanks, "link validator". :P

See http://download.oracle.com/javase/6/docs/api/java/net/Inet4Address.html or http://www.perlmonks.org/?node_id=221512, or http://en.wikipedia.org/wiki/IPv4#Address_representations, for some more details.

Java understands these formats as well (as does .net, as well as any decent OS), and parses the address correctly whether it contains 1, 2, 3, or 4 parts.

If you want to check that a would-be address actually looks like "xxx.xxx.xxx.xxx", then you'll probably want to explicitly check that using a pattern, or using a validation library that considers 32-bit numbers as invalid addresses (even though they are valid). I wouldn't bother, though -- if you use the lookup functions provided, you can accept an address in any standard format and it will work.

(All this mess changes with IPv6; there's a much stricter format, and you can't just type in some 36-digit number and expect it to work. But the platform still knows how to parse an address, and you should trust it to do so.)

眼泪淡了忧伤 2024-12-13 17:49:58

查看 Guava InetAddresses 类包含用于处理 IP 地址的静态实用程序方法。 (据我了解,它在幕后使用 sun.net.util.IPAddressUtil 类。)

System.out.println(InetAddresses.isInetAddress("400")); // false

Check out Guava's InetAddresses class which contains static utility methods for working with IP addresses. (As I understand it uses the sun.net.util.IPAddressUtil class behind the scenes.)

System.out.println(InetAddresses.isInetAddress("400")); // false
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文