Java determines whether an IP is within a network segment
Calculate how many IP addresses are in Ip/mask: 2 (32-mask) of the second party
For example: 192.168.3.4/30 has a total of 2 (32-30) of the second-order IP
Java determines whether an IP ip/mask ip+ mask within a network segment
Package Com.ip;
public class Iptest {
public static void Main (string[] args) {
System.out.println (Isinrange ("192.168.1.127", "192.168.1.64/26"));
System.out.println (Isinrange ("192.168.1.2", "192.168.0.0/23"));
System.out.println (Isinrange ("192.168.0.1", "192.168.0.0/24"));
System.out.println (Isinrange ("192.168.0.0", "192.168.0.0/32"));
}
public static Boolean Isinrange (string IP, string cidr) {
string[] ips = Ip.split ("\.");
int ipaddr = (Integer.parseint (ips[0)) << 24)
| (Integer.parseint (ips[1]) << 16)
| (Integer.parseint (ips[2]) << 8) | Integer.parseint (Ips[3]);
int type = Integer.parseint (Cidr.replaceall (". *", ""));
int mask = 0xFFFFFFFF << (32-type);
String Cidrip = Cidr.replaceall ("/.*", "");
string[] Cidrips = Cidrip.split ("\;");
int cidripaddr = (Integer.parseint (cidrips[0)) << 24)
| (Integer.parseint (cidrips[1]) << 16)
| (Integer.parseint (cidrips[2]) << 8)
| Integer.parseint (Cidrips[3]);
Return (ipaddr & mask) = = (Cidripaddr & mask);
}
}
How does Java judge the existence of a network segment based on IP? 0
For example, network segment:
192.168.2.0/24
192.168.1.0/24
192.168.34.0/26
192.168.33.0/26
String[] Subnetsmasks = {...};
collection<subnetinfo> subnets = new arraylist<subnetinfo> ();
for (String subnetmask:subnetsmasks) {
Subnets.add (New Subnetutils (SubnetMask). GetInfo ());
}
String ipaddress = ...;
for (Subnetinfo subnet:subnets) {
if (Subnet.isinrange (IPAddress)) {
System.out.println ("IP address" + IPAddress + "are in range" + subnet.getcidrsignature ());
}
}
/**
* Determine if IP is in the specified network segment
* @author DH
* @param Iparea
* @param IP
* @return Boolean
*/
public static Boolean ipisinnet (string iparea, string IP) {
if (Iparea = null)
throw new NullPointerException ("IP segment cannot be empty.") ");
if (IP = null)
throw new NullPointerException ("IP cannot be empty.") ");
Iparea = Iparea.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 (!iparea.matches (REGX_IPB) | | |!ip.matches (REGX_IP))
return false;
int idx = iparea.indexof ('-');
String[] sips = iparea.substring (0, IDX). Split ("//;");
string[] Sipe = iparea.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]);
IPT = IPT << 8 | Integer.parseint (Sipt[i]);
}
if (IPs > Ipe) {
Long T = IPs;
ips = IPE;
Ipe = t;
}
Return IPs <= IPT && IPT <= Ipe;
}