Determine whether two IP addresses are in the same CIDR Block

Source: Internet
Author: User

Features

  • Determines whether an IP address is valid.

  • Determine whether two IP addresses are in the same CIDR Block

  • Determine the relationship between two IP addresses

Knowledge preparation
  • IP protocol

  • Subnet Mask

  • Java

  • Regular Expression

Basic Principles
IP address range0.0.0.0 ~ 255.255.255.255, including the mask address. IP address Division
  • Class A address: 1.0.0.1 ~ 126.00000000254

  • Class B address: 128.0.0.1 ~ 191.00000000254

  • Class C address: 192.168.0.0 ~ 192.168.255.255

  • Class D address: 224.0.0.1 ~ 239.00000000254

  • Class E address: 240.0.0.1 ~ 255.255.255.254

Determine whether two IP addresses are in the same CIDR BlockTo determine whether two IP addresses are in the same CIDR Block, perform and calculate the IP addresses and subnet masks respectively. The result is a network number. If the network number is the same, the IP addresses are in the same subnet, otherwise, it is not in the same subnet. For example, if the subnet mask 255.255.254.0 is selected, the preceding two IP addresses and the mask are used respectively, as shown in:
211.95.165.24 11010011 01011111 10100101 0001100000000000254.0 11111111 11111111 111111110 00000000 and the result is: 11010011 01011111 10100100 00000000

211.95.164.78 11010011 01011111 10100100 010011101_254.0 11111111 11111111 111111110 00000000 and the result is: 11010011 01011111 10100100 00000000
We can see that the obtained results (the result is the network address) are the same, so we can determine that the two IP addresses are in the same subnet. If no subnet is divided, the subnet mask of the-type network is 255.0.0.0, The subnet mask of the B-type network is 255.255.0.0, And the subnet mask of the C-type network is 255.255.255.255.0. The default subnet mask is 255.255.255.0. ImplementationImplemented in Java, mainly for IPv4 addresses.

The code implementation includes the following annotations ):


Package org.slive.net; import java.net. UnknownHostException; import java. util. regex. Pattern;/*** <pre> * IP address range: * 0.0.0.0 ~ 255.255.255.255, including the mask address. ** IP address division: * Class A address: 1.0.0.1 ~ 126.20.255.254 * Class B address: 128.0.0.1 ~ 191.255.255.254 * C Class address: 192.168.0.0 ~ 192.168.255.255 * D Class address: 224.0.0.1 ~ 239.00000000254 * Class E address: 240.0.0.1 ~ 255.255.255.254 ** how to determine whether two IP addresses are in the same CIDR Block? * to determine whether two IP addresses are in the same CIDR Block, perform and calculate the IP addresses and subnet masks respectively, the result 1 is a network number. If the network number is the same, it is in the same subnet. Otherwise, it is not in the same subnet. * Example: if the subnet mask 255.255.254.0 is selected, the preceding two IP addresses and the mask are respectively used for calculation, as shown in: * 211.95.165.24 11010011 01011111 10100101 00011000*201710000254.0 11111111 11111111 111111110 00000000 * and the result is: 11010011 01011111 10100100 00000000 ** 211.95.164.78 11010011 01011111 10100100 01001110*00000000254.0 11111111 11111111 111111110 00000000 * and the result is: 11010011 01011111 10100100 00000000, the obtained results (the Network Address) are the same, so we can determine that the two IP addresses are in the same subnet. ** If no subnet is divided, the subnet mask of the Class A network is 255.0.0.0, The subnet mask of the Class B network is 255.255.0.0, And the subnet mask of the class C network is 255.255.255.0, by default, the subnet mask is the regular expression of 255.255.255.0 ** @ author Slive */public class 255.4util {// IpV4, used to determine whether the IpV4 address is legal private static final String limit 4_regex = "(\ d | [1-9] \ d | 1 \ d {2} | 2 [0- 4] \ d | 25 [0-5]) (\\. (\ d | [1-9] \ d | 1 \ d {2} | 2 [0-4] \ d | 25 [0-5]) {3}) "; // system subnet mask, which consists of an ip address private int mask; // 1 represents Class A, 2 represents Class B, and 3 represents Class C; 4 represents other types of public final static int IP _ A_TYPE = 1; public final static int IP_ B _TYPE = 2; public final static int IP_C_TYPE = 3; public final static int IP_OTHER_TYPE = 4; // Class A address range: 1.0.0.1 --- 126.20.254 private static int [] IpATypeRange; // Class B address range: 128.0.0.1 --- 191.20.255.254 private static int [] IpBTypeRange; // Class C address range: 192.168.0.0 ~ 192.168.255.255 private static int [] IpCTypeRange; // default mask private static int DefaultIpAMask; private static int DefaultIpBMask; private static int DefaultIpCMask; // initialize static {IpATypeRange = new int [2]; IpATypeRange [0] = getIpV4Value ("1.0.0.1"); IpATypeRange [1] = getIpV4Value ("126.00000000254 "); ipBTypeRange = new int [2]; IpBTypeRange [0] = getIpV4Value ("128.0.0.1"); IpBTypeRange [1] = GetIpV4Value ("secret"); IpCTypeRange = new int [2]; IpCTypeRange [0] = getIpV4Value ("192.168.0.0"); IpCTypeRange [1] = getIpV4Value ("192.168.255.255 "); defaultIpAMask = getIpV4Value ("255.0.0.0"); bandwidth = getIpV4Value ("255.255.0.0"); bandwidth = getIpV4Value ("255.255.255.0");}/*** default 255.255.255.255.0 */public 255.4util () {mask = getIpV4Value ("00000000255.0");}/*** @ param mas If the format is invalid, an UnknownError Error error is thrown */public writable 4util (String masks) {mask = getIpV4Value (masks ); if (mask = 0) {throw new UnknownError () ;}} public int getMask () {return mask ;}/ *** compares whether two IP addresses are in the same CIDR block, if both are valid addresses and both are invalid addresses, the system can compare them normally. * If either is invalid, false is returned; * Note that the IP address here refers to an address such as "192.168.1.1" and does not include mask * @ return */public boolean checkSameSegment (String ip1, String ip2) {return checkSam ESegment (ip1, ip2, mask);}/*** checks whether two IP addresses are in the same CIDR block. If both are valid addresses and both are invalid addresses, they can be compared normally; * If one of the IP addresses is not valid, false is returned. * Note that the IP address here refers to the address "192.168.1.1" * @ return */public static boolean checkSameSegment (String ip1, String ip2, int mask) {// checks whether IPV4 is valid if (! IpV4Validate (ip1) {return false;} if (! Listen 4validate (ip2) {return false;} int ipValue1 = getIpV4Value (ip1); int ipValue2 = getIpV4Value (ip2); return (mask & ipValue1) = (mask & ipValue2);}/*** checks whether two IP addresses are in the same CIDR block. If both IP addresses are valid and both IP addresses are invalid, they can be normally compared; * If one of the IP addresses is not valid, false is returned. * Note that the IP address here refers to the address "192.168.1.1" * @ return */public static boolean checkSameSegmentByDefault (String ip1, String ip2) {int mask = getdefamasmaskvalue (ip1); // obtain the default Mask return checkSameSegment (ip1, ip2, mask );} /*** obtain the ip value and mask value and result * @ param ipV4 * @ return 32bit value */public int getSegmentValue (String ipV4) {int ipValue = getIpV4Value (ipV4 ); return (mask & ipValue);}/*** obtain the ip and mask values and the result * @ param ipV4 * @ return 32bit value */public static int getSegmentValue (String ip, int mask) {int ipValue = getIpV4Value (ip); return (mask & ipValue);}/*** determines whether the ipV4 or mask address is valid, use regular expressions to determine * @ param ipv4 */public static boolean ipV4Validate (String ipv4) {return ipv4Validate (ipv4, IPV4_REGEX);} private static boolean ipv4Validate (String addr, string regex) {if (addr = null) {return false;} else {return Pattern. matches (regex, addr. trim () ;}}/*** compares two IP addresses. If both are valid IP addresses, 1 indicates that ip1 is greater than ip2,-1 indicates that ip1 is less than ip2, and 0 indicates equal; * If one of the IP addresses is not valid, for example, if ip2 is not a valid IP address, if ip1 is greater than ip2, 1 is returned. If both IP addresses are invalid, 0 is returned; * Note that the IP address here refers to an address such as "192.168.1.1", excluding mask * @ return */public static int compare1_4s (String ip1, String ip2) {int result = 0; int ipValue1 = getIpV4Value (ip1); // obtain the 32bit value of ip1 int ipValue2 = getIpV4Value (ip2); // obtain the 32bit value of ip2 if (ipValue1> ipValue2) {result =-1;} else if (ipValue1 <= ipValue2) {result = 1;} return result;}/*** checks ipV4 types, including class, * @ param ipV4 * @ return for Class B, Class C, and other C, D, and broadcast classes. return 1 for Class A, return 2 for Class B, and return 3 for Class C; 4 represents Class D */public static int check1_4type (String ipV4) {int inValue = getIpV4Value (ipV4 ); if (inValue> = IpCTypeRange [0] & inValue <= IpCTypeRange [1]) {return IP_C_TYPE ;} else if (inValue >=ipbtyperange [0] & inValue <= IpBTypeRange [1]) {return IP_ B _TYPE ;} else if (inValue> = IpATypeRange [0] & inValue <= IpATypeRange [1]) {return IP_A_TYPE;} return IP_OTHER_TYPE;}/*** get the default mask value, if IpV4 is A Class A address, {@ linkplain # DefaultIpAMask} is returned. * If IpV4 is A Class B address, {@ linkplain # DefaultIpBMask} is returned }, similarly, * @ param anyIpV4 any valid IpV4 * @ return mask 32bit value */public static int getdefamasmaskvalue (String anyIpV4) {int checkIpType = checkult4type (anyIpV4); int maskValue = 0; switch (checkIpType) {case IP_C_TYPE: maskValue = DefaultIpCMask; break; case IP_ B _TYPE: maskValue = signature; break; case IP_A_TYPE: maskValue = DefaultIpAMask; break; default: maskValue = signature ;} return maskValue;}/*** get the default mask address. The class A address corresponds to 255.0.0.0, and the class B address corresponds to 255.255.0.0, * C class and other corresponding response 255.255.0 * @ param anyIp * @ return mask String indicates */public static String getdefamasmaskstr (String anyIp) {return trans2IpStr (getdefamasmaskvalue (anyIp ));} /*** convert the ip 32bit value to a String in the format of "192.168.0.1" * @ param ipValue 32bit * @ return */public static String trans2IpStr (int ipValue) {// ensure that each address is a positive integer return (ipValue> 24) & 0xff) + ". "+ (ipValue> 16) & 0xff) + ". "+ (ipValue> 8) & 0xff) + ". "+ (ipValue & 0xff );} /*** convert the ip byte array value to a String such as "192.168.0.1" * @ param ipBytes 32bit value * @ return */public static String trans2IpV4Str (byte [] ipBytes) {// ensure that each address is a positive integer return (ipBytes [0] & 0xff) + ". "+ (ipBytes [1] & 0xff) + ". "+ (ipBytes [2] & 0xff) + ". "+ (ipBytes [3] & 0xff);} public static int getIpV4Value (String ipOrMask) {byte [] addr = getIpV4Bytes (ipOrMask ); int address1 = addr [3] & 0xFF; address1 | = (addr [2] <8) & 0xFF00); address1 | = (addr [1] <16) & 0xFF0000); address1 | = (addr [0] <24) & 0xFF000000); return address1;} public static byte [] getIpV4Bytes (String ipOrMask) {try {String [] addrs = ipOrMask. split ("\\. "); int length = addrs. length; byte [] addr = new byte [length]; for (int index = 0; index <length; index ++) {addr [index] = (byte) (Integer. parseInt (addrs [index]) & 0xff) ;}return addr ;}catch (Exception e) {} return new byte [4] ;}}


Application

Public static void main (String [] args) throws UnknownHostException {// judge the relationship between the two ip addresses String ip1 = "10.8.9.116"; String ip2 = "10.8.9.10"; System. out. println ("ip1 is greater than ip2? "+ (Compare00004s (ip1, ip2)> 0); String ip3 =" 10.8.8.116 "; String ip4 =" 10.10.9.10 "; System. out. println (" ip3 greater than ip4? "+ (Compare00004s (ip3, ip4)> 0); // determines whether the two ip addresses are in the same network segment int mask1 = getIpV4Value (" 255.255.255.0 "); int mask2 = getIpV4Value ("255.255.0.0"); System. out. println ("is ip1 and ip2 in the same network segment? "+ (CheckSameSegment (ip1, ip2, mask1); System. out. println (" is ip3 and ip4 in the same network segment? "+ (CheckSameSegment (ip3, ip4, mask2); // determines whether ip5 is in the range of ip1 and ip2 String ip5 =" 10.8.8.8 "; // assume that ip1 and ip2 are in the same network segment, and ip1 is the starting address, and ip2 is the ending address, ip1 <= 1 // compare whether ip1 and ip5 are in the same network segment if (checkSameSegment (ip1, ip5, mask1 )) {// determine whether ip5 is in the range of ip1 and ip2 if (compare00004s (ip5, ip1)> = 0) & (compare00004s (ip5, ip2) <= 0) {System. out. println ("ip5 in ip1-ip2 range");} else if (compare00004s (ip5, ip1) <0) {System. out. println ("ip5 is not in the ip1-ip2 range because ip5 is smaller than ip1");} else {System. out. println ("ip5 is out of the ip1-ip2 range because ip5 is greater than ip2") ;}} else {System. out. println ("ip5 is out of the ip1-ip2 range because ip5 is not in the IP 1 segment ");}}

Summary
  • Understand the expression in progress and the expression used to determine whether the IP address is valid

  • Measure the test taker's knowledge about the principles of determining whether an IpV4 address is in the same CIDR block.

Optimization and Expansion
  • Another method to determine the validity of an IpV4 address (without passing a positive expression)

  • Determines whether IpV4 is A Class A address, B address, or broadcast address.

  • Whether multiple IpV4 addresses are in the same CIDR Block

  • Client and server security policy implementation-restrict user IP addresses to log on to the system


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.