In the past, the project used to implement IP Address Access Control. I forgot where to transfer the IP address and thought I had changed it. Go directlyCode
Public Class Iptest { /* ** Determines whether the IP address is in the specified range; */ Boolean I; Public Static Boolean ipisvalid (string ipsection, string IP ){ If (Ipsection = Null ) Throw New Nullpointerexception ( " IP segment cannot be blank! " ); If (IP = Null ) Throw New Nullpointerexception ( " IP address cannot be blank! " ); Ipsection =Ipsection. Trim (); IP = IP. Trim (); final string regx_ip = " (25 [0-5] | 2 [0-4] \ d | 1 \ D {2} | [1-9] \ d | \ D) \\.) {3} (25 [0-5] | 2 [0-4] \ d | 1 \ D {2} | [1-9] \ d | \\ d) " ; Final string regx_ipb = Regx_ip + " \\- " + Regx_ip; If (! Ipsection. Matches (regx_ipb) |! IP. Matches (regx_ip )) Return False ; Int Idx = ipsection. indexof ( ' - ' ); String [] sips = Ipsection. substring ( 0 , Idx). Split ( " \\. " ); String [] sipe = Ipsection. substring (idx + 1 ). Split (" \\. " ); String [] sipt = IP. Split ( " \\. " ); Long IPS = 0l , IPE = 0l , IPT = 0l ; For ( Int I =0 ; I < 4 ; ++ I) {IPS = IPS < 8 | Integer. parseint (Sips [I]); IPE = IPE < 8 | Integer. parseint (sipe [I]); EPT = IPT < 8 | Integer. parseint (sipt [I]);} If (IPS> IPE ){ Long T = IPS = IPE; IPE = T ;} Return IPS <= IPT & EPT <= IPE ;} Public Static Void Main (string [] ARGs ){ If (Ipisvalid ( " 10.118.128.0-10.118.255.255 " ," 10.118.202.2 " ) {System. Out . Println ( " The IP address belongs to this CIDR block. " );} Else System. Out . Println ( " The IP does not belong to this CIDR block. " );}}
simply put, IPv4 is divided into four segments with a length of 32 bits. Then, the starting and ending IP addresses and each segment of the IP addresses to be verified are upgraded to a value of 0 at the end of less than 8 digits. After all the IP addresses are upgraded, check whether the IP addresses to be verified are in this segment.