Mutual conversion of ip address and integer

Project github address: bitcarmanlee easy-algorithm-interview-and-practice
often have students private messages or leave messages to ask related questions, V number bitcarmanlee. The classmates of star on github, within the scope of my ability and time, I will try my best to help you answer related questions and make progress together.

1. Why need to convert ip to integer

As for the ip address of ipv4, if string storage is used, the space occupied is relatively large. For example, the string 0.1.2.3 requires 7 bytes. For the string 255.255.255.255, 15 bytes are required. Overall, it takes 7-15 bytes to store an IP address.

So is there a better way to store in actual use, so as to save storage space? The answer is yes.
ipv4 is essentially a 32-bit binary string. An int integer is exactly 4 bytes and 32 bits, so an int type integer can just represent an ipv4 address. Therefore, we use a 4-byte int type number to represent an ip address, which can achieve the goal of saving space.

2. ip address to integer

Let's take a look at how to implement ip address to integer.

public class Ipaddress {

    public static boolean isIpv4Address(String ip) {
        if (StringUtils.isEmpty(ip)) {
            return false;
        }

        String[] lines = ip.split("\\.");
        if (lines.length != 4) return false;

        for(String pattern : lines) {
            try {
                int number = Integer.parseInt(pattern);
                if (number >= 0 && number <= 255) continue;
                else return false;
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return true;
    }


    public static int ip2int(String ip) {
        if (!isIpv4Address(ip)) {
            throw new RuntimeException("invalid ip address");
        }

        int result = 0;
        String[] lines = ip.split("\\.");
        for(String pattern: lines) {
            int number = Integer.parseInt(pattern);
            result = number | (result << 8);
        }

        return result;
    }
    
    public static void main(String[] args) {
        String ip = "125.213.100.123";
        int result = ip2int(ip);
        System.out.println(result);
        System.out.println(125*256*256*256+213*256*256+100*256+123);
    }
}

The output of the code is:

2111136891
2111136891

The idea of ​​the above code:
1. First judge the legitimacy of the input ip address.
2. Separate ip by. And divide it into 4 sections.
3. Move the first segment to the left by 24 bits, the second segment to the left by 16 bits, the third segment to the left by 8 bits, and the fourth segment remains unchanged. Add the results to get the final result. The specific implementation logic is
result = number | (result << 8)this line.
4. If it is the most violent method, 125*256*256*256+213*256*256+100*256+123this part of the main method realizes the logic mentioned in Article 3, and the final result obtained by the two is the same.

3. Integer to IP address

Conversely, if we have an integer and want to convert it to an ip address, it is actually the reverse process of the above.

import org.apache.commons.lang3.StringUtils;

public class Ipaddress {

    public static String int2ip(int num) {
        return ((num >> 24) & 0xff) + "." +
                ((num >> 16) & 0xff) + "." +
                ((num >> 8) & 0xff) + "." +
                (num & 0xff);
    }

    public static void main(String[] args) {
        int num = 2111136891;
        String ip = int2ip(num);
        System.out.println(ip);
    }
}

The specific logic is:
The first segment of the ip address is num shifted right by 24 bits and then the lower 8 bits are taken
. The second segment is num shifted right by 16 bits and then the lower 8 bits are taken
. The third segment of the ip address is num shifted right by 8. Take the lower 8 bits after the bit
, the fourth segment of the ip address is num and take the lower 8 bits

Guess you like

Origin blog.csdn.net/bitcarmanlee/article/details/113662877