SoFunction
Updated on 2025-04-11

How to implement CIDR to IP segment in Java

1. The core concept of CIDR

CIDR (Classless Inter-Domain Routing, Classless Inter-Domain Routing) is a network addressing method for efficient allocation and management of IP addresses. It replaces the traditional IP address classification (A/B/C class), and achieves finer address division and routing aggregation through flexible network prefix length (subnet mask), significantly improves the utilization of IP addresses and reduces the routing table size.

1. Limitations of traditional IP classification

Class A/B/C address: Traditionally divide IP addresses into fixed categories (such as Class A: /8, Class B: /16, Class C: /24).

Problem: Address assignment is inflexible. For example, an institution that requires 500 IPs must apply for a Class B address (65,536 IPs), causing a lot of waste.

2. CIDR solutions

No category division: no longer rely on fixed categories, allowing network prefixes of any length (such as /17, /22).

Format: IP address/prefix length (e.g. 192.168.1.0/24), where:

Prefix length: The number of bits in the network part (such as /24 means that the first 24 bits are the network address).

Host part: The remaining number of bits is used for the host address (for example, the host part of /24 has 8 bits and supports 256 IPs).

CIDR is the basic technology of modern Internet, which solves the rigid problem of traditional IP classification. Through flexible network prefix management and routing aggregation, the efficiency of IP addresses is significantly improved and is the core tool for network planning and operation and maintenance.

2. Analysis of the principle of implementation

So how to use Java to implement "CIDR to IP segment"?

2.1 Separate IP address and mask

For example, the input string needs to be split into IP parts and mask bits. For example, "221.236.192.0/21" needs to be split into IP address 221.236.192.0 and mask 21.

2.2 Convert IP address to 32-bit integer form

For example, convert each part (four octets) into binary and splice it into a 32-bit integer. For example, after 221.236.192.0 is converted into binary, it is calculated again.

2.3 Calculate the subnet mask based on the number of mask bits

If the mask is 21 bits, the first 21 bits of the subnet mask are 1 and the next is 0. This mask can be generated using bit operations. For example, the integer form of the subnet mask is 0xFFFFFF << (32 - 21), and then operate with 0xFFFFFF to ensure that the high bit is correct.

Network addresses can be obtained by bitwise operations of the integer form of the IP address and the subnet mask. The starting IP is this network address.

The broadcast address is the host part of the network address. It can be obtained by bitwise or by inverting the network address with the subnet mask. The end IP is the broadcast address.

Then you need to convert the start and end IP of these two integer forms back to dotted decimal string form. For example, split the integer into four octets, convert each part into a decimal number, and splice it into an IP string.

2.4 Program method implementation steps

Details that may need to be noted:

Input verification: Make sure that the CIDR is formatted correctly, the IP parts are between 0-255, and the mask bit count is between 0-32.

To deal with integer overflow problem during IP conversion, Java should use long type to handle 32-bit unsigned integers to avoid the problem of sign bits.

When converting IP addresses, especially when dealing with each octet, pay attention to the correct use of shift and bitmask.

Test the boundary situation, for example, when the mask is 32, the starting and ending IPs are the same; when the mask is 0, the entire address range is 0.0.0.0 to 255.255.255.255.255.

Now, the specific steps:

Split the input string into the IP and mask parts.

String[] parts = ("/");
String ip = parts[0];
int prefix = (parts[1]);

Convert IP addresses to 32-bit integers (use long to avoid symbolic problems).

String[] octets = ("\\.");

long ipLong = ((octets[0]) << 24) |

((octets[1]) << 16) |

((octets[2]) << 8) |

(octets[3]);

Calculate the subnet mask.

long mask = 0xFFFFFFFFL << (32 - prefix);

Calculate the network address (start IP).

long startIp = ipLong & mask;

Calculate the broadcast address (end IP).

long endIp = startIp | (~mask);

However, it should be noted here that bit operations in Java will invert all 64 bits, so you need to use 0xFFFFFFFL to mask, leaving only the lower 32 bits:

long endIp = startIp | (~mask & 0xFFFFFFFFL);

Convert startIp and endIp into dotted decimal strings.

private static String longToIp(long ip) {
    return ("%d.%d.%d.%d",
        (ip >> 24) & 0xFF,
        (ip >> 16) & 0xFF,
        (ip >> 8) & 0xFF,
        ip & 0xFF);
}

Encapsulate the result into the map.

Map<String, String> result = new HashMap<>();
("start", longToIp(startIp));
("end", longToIp(endIp));

Then you need to consider input verification, such as checking whether the length of parts is 2, whether the prefix is ​​between 0 and 32, whether the IP has four octets, and whether each value is between 0-255.

In summary, the writing method should include:

  • Enter verification to ensure that the CIDR format is correct, the IP segments are valid, and the mask is valid.
  • Convert IP to long integer.
  • Calculate the subnet mask, network address and broadcast address.
  • Convert back to IP string.
  • Encapsulate the result into the map.

Some exceptions may also need to be handled, such as NumberFormatException, which may need to be thrown at this time, or null may be returned, but the user may need a robust method. In the example code, it is possible to simplify processing, assuming the input is correct, or adding necessary verification.

Now, based on the above analysis, write Java code.

3. Complete implementation of Java code

The following is the Java method that implements this feature, including detailed comments and input verification:

import ;
import ;

public class CidrConverter {

    public static Map&lt;String, String&gt; splitCidr(String cidr) {
        Map&lt;String, String&gt; result = new HashMap&lt;&gt;();

        // Verify the input format (e.g. "221.236.192.0/21")        if (!("^(\\d+\\.){3}\\d+/\\d+$")) {
            throw new IllegalArgumentException("Invalid CIDR format");
        }

        String[] parts = ("/");
        String ipAddress = parts[0];
        int prefixLength = (parts[1]);

        // Verify the number of subnet mask bits        if (prefixLength &lt; 0 || prefixLength &gt; 32) {
            throw new IllegalArgumentException("Invalid prefix length");
        }

        // Convert IP address to 32-bit integer (use long to avoid symbol problems)        String[] ipOctets = ("\\.");
        if ( != 4) {
            throw new IllegalArgumentException("Invalid IP address");
        }

        long ipLong = 0;
        for (int i = 0; i &lt; 4; i++) {
            int octet = (ipOctets[i]);
            if (octet &lt; 0 || octet &gt; 255) {
                throw new IllegalArgumentException("Invalid IP octet");
            }
            ipLong |= (long) octet &lt;&lt; (24 - (8 * i));
        }

        // Calculate the subnet mask        long mask = 0xFFFFFFFFL &lt;&lt; (32 - prefixLength);

        // Calculate the starting IP (network address)        long startIp = ipLong &amp; mask;

        // Calculation end IP (broadcast address)        long endIp = startIp | (~mask &amp; 0xFFFFFFFFL);

        // Convert to dotted decimal string        ("start", longToIp(startIp));
        ("end", longToIp(endIp));

        return result;
    }

    // Convert 32-bit integers to IP strings    private static String longToIp(long ip) {
        return ((ip &gt;&gt; 24) &amp; 0xFF) + "." +
               ((ip &gt;&gt; 16) &amp; 0xFF) + "." +
               ((ip &gt;&gt; 8) &amp; 0xFF) + "." +
               (ip &amp; 0xFF);
    }

    // Test cases    public static void main(String[] args) {
        String cidr = "221.236.192.0/21";
        Map&lt;String, String&gt; ipRange = splitCidr(cidr);
        ("Start IP: " + ("start")); // 221.236.192.0
        ("End IP: " + ("end"));   // 221.236.199.255
    }
}

Code description

1. Enter verification

  • Check CIDR format legality using regular expressions
  • Verify the number of bits of subnet mask (0-32)
  • Check whether the four octets of the IP address are legal (0-255)

2. Core computing logic

  • Convert IP addresses to 32-bit integers (use long to avoid symbolic problems)
  • Calculate subnet mask, network address and broadcast address through bit operations

3. Sample test

When inputting 221.236.192.0/21, output:

Start IP: 221.236.192.0
End IP: 221.236.199.255

Key formulas

  • Subnet mask: mask = 0xFFFFFFL << (32 - prefixLength)
  • Network address: startIp = ipLong & mask
  • Broadcast address: endIp = startIp | (~mask & 0xFFFFFFFL)

Things to note

  • Input legality: Make sure that the CIDR is formatted correctly (for example, 192.168.1.0/24)
  • Performance optimization: bit operations directly operate memory, extremely efficient
  • Large address processing: Use long to avoid the symbolic problem of int

This is the end of this article about how Java can implement CIDR to IP segment. For more related content on Java CIDR to IP segment, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!