检查IPv4地址是否在私有范围内

时间:2011-11-15 18:31:46

标签: java networking

在Python中,使用IPy模块可以执行以下操作:

 >>> ip.iptype()
'PRIVATE'

是否有一个库或简单的方法来在Java中执行相同的操作?

3 个答案:

答案 0 :(得分:10)

似乎不完全正确但InetAddress有一些isXX()方法,例如:isAnyLocalAddress()isSiteLocalAddress()

答案 1 :(得分:4)

我相信Inet4Address.isSiteLocalAddress()是你想要的方法。这是一个例子:

public final class IPFreely
{
    public static void main(String[] args)
    {
        byte[] rawAddress1 =
        { 10, 0, 0, 0 };
        byte[] rawAddress2 =
        { 10, 0, 32, 0 };
        byte[] rawAddress3 =
        { (byte) 172, 16, 0, 0 };
        byte[] rawAddress4 =
        { (byte) 192, (byte) 168, 0, 0 };

        testIpAddress(rawAddress1);
        testIpAddress(rawAddress2);
        testIpAddress(rawAddress3);
        testIpAddress(rawAddress4);
    }

    public static void testIpAddress(byte[] testAddress)
    {
        Inet4Address inet4Address;

        try
        {
            inet4Address = (Inet4Address) InetAddress.getByAddress(testAddress);

            System.out.print("inet4Address.isSiteLocalAddress(): ");
            System.out.println(inet4Address.isSiteLocalAddress());
        }
        catch (UnknownHostException exception)
        {
            System.out.println("UnknownHostException");
        }
    }
}

答案 2 :(得分:3)

如果InetAddress对您不起作用,那么将python code转换为java后应该很容易:

IPv4ranges = {
    '0':                'PUBLIC',   # fall back
    '00000000':         'PRIVATE',  # 0/8
    '00001010':         'PRIVATE',  # 10/8
    '01111111':         'PRIVATE',  # 127.0/8
    '1':                'PUBLIC',   # fall back
    '1010100111111110': 'PRIVATE',  # 169.254/16
    '101011000001':     'PRIVATE',  # 172.16/12
    '1100000010101000': 'PRIVATE',  # 192.168/16
    '111':              'RESERVED'  # 224/3
    }

def iptype(self):
    if self._ipversion == 4:
        iprange = IPv4ranges
    elif self._ipversion == 6:
        iprange = IPv6ranges
    else:
        raise ValueError("only IPv4 and IPv6 supported")

    bits = self.strBin()
    for i in xrange(len(bits), 0, -1):
        if bits[:i] in iprange:
            return iprange[bits[:i]]
    return "unknown"