Java IP address for the internal network IP or public network IP method

  • 2020-04-01 03:37:13
  • OfStack

This article illustrates how Java determines whether an IP address is an Intranet IP or a public IP address. Share with you for your reference. Specific analysis is as follows:

In the TCP/IP protocol, three IP address regions are reserved as private addresses, and their address ranges are as follows:

10.0.0.0 ~ 10.255.255.255
172.16.0.0/ 12:17 2.16.0.0 ~ 172.31.255.255
192.168.0.0/16:19 2.168.0.0 ~ 192.168.255.255

So, directly on the code:

public static boolean internalIp(String ip) {
    byte[] addr = IPAddressUtil.textToNumericFormatV4(ip);
    return internalIp(addr);
} public static boolean internalIp(byte[] addr) {
    final byte b0 = addr[0];
    final byte b1 = addr[1];
    //10.x.x.x/8
    final byte SECTION_1 = 0x0A;
    //172.16.x.x/12
    final byte SECTION_2 = (byte) 0xAC;
    final byte SECTION_3 = (byte) 0x10;
    final byte SECTION_4 = (byte) 0x1F;
    //192.168.x.x/16
    final byte SECTION_5 = (byte) 0xC0;
    final byte SECTION_6 = (byte) 0xA8;
    switch (b0) {
        case SECTION_1:
            return true;
        case SECTION_2:
            if (b1 >= SECTION_3 && b1 <= SECTION_4) {
                return true;
            }
        case SECTION_5:
            switch (b1) {
                case SECTION_6:
                    return true;
            }
        default:
            return false;
    }
}

I hope this article has been helpful to your Java programming.


Related articles: