addr是非法的长度 [英] addr is of illegal length

查看:683
本文介绍了addr是非法的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查ipAddress是否属于私有类别。所以我在下面写了这个方法。我将此作为例外 -

I am checking whether the ipAddress is in Private Category or not. So I wrote this method below. And I am getting this as an exception-

java.net.UnknownHostException: addr is of illegal length
    at java.net.InetAddress.getByAddress(InetAddress.java:948)
    at java.net.InetAddress.getByAddress(InetAddress.java:1324)

ipAddress(172.18.36.81)is String

ipAddress (172.18.36.81) is String

if(isPrivateIPAddress(ipAddress)) {

            return null;
        }


private static boolean isPrivateIPAddress(String ipAddress) {

    byte[] byteArray = null;
    InetAddress ia = null;
    try {
        byteArray = ipAddress.getBytes("UTF-16LE");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


    try {
        ia = InetAddress.getByAddress(byteArray);
    } catch (UnknownHostException e) {

        e.printStackTrace();
    }

    return ia.isSiteLocalAddress();
}


推荐答案

我觉得你误解了如何将IP地址从 String 转换为 byte [] 。正确的方法是将 String 解析为 int 的序列,然后将其中的每一个转换为一个字节。但幸运的是, InetAddress 已经有一个方法可以为你处理,所以你可以写:

I think you've misunderstood how to convert an IP address from String to byte[]. The proper way to do that is to parse String to a sequence of ints, and then cast each of those to a byte. But fortunately, InetAddress already has a method to handle that for you, so you can just write:

private static boolean isPrivateIPAddress(String ipAddress)
{
    return InetAddress.getByName(ipAddress).isSiteLocalAddress();;
}

(以及您想要的任何有效性检查和错误处理)。

(together with whatever validity-checking and error-handling you want).

请注意,上述内容还将使用DNS查找处理主机名。如果您不想这样,您需要使用以下内容预先检查IP地址:

Note that the above will also handle hostnames, by using DNS lookup. If you don't want that, you'll need to pre-check the IP-address, using something like this:

if(! Pattern.matches("(\\d{1,3}\\.){3}\\d{1,3}", ipAddress)
    throw new IllegalArgumentException();

如果你只支持IPv4就行了。

if you're O.K. with only supporting IPv4.

这篇关于addr是非法的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆