/*** Test whether the network can be connected smoothly *@paramserviceurl *@return */ Public Static Booleanisconnection (String serviceurl) {Try{URL URL=NewURL (serviceurl); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout (2000);//2 seconds is timed outConn.setreadtimeout (2000); intState =Conn.getresponsecode (); if(state = = 200) { return true; } } Catch(Exception e) {return false; } return false; }
/*** Test if it belongs to a network segment *@paramipsection *@paramIP *@return */ Public Static Booleanipisvalid (String ipsection, String IP) {if(Ipsection = =NULL) Throw NewNullPointerException ("IP segment cannot be empty!") "); if(IP = =NULL) Throw NewNullPointerException ("IP cannot be empty!") "); Ipsection=Ipsection.trim (); IP=Ip.trim (); FinalString 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) "; FinalString REGX_IPB = regx_ip + "\\-" +regx_ip; if(!ipsection.matches (REGX_IPB) | |!ip.matches (regx_ip))return false; intIDX = Ipsection.indexof ('-'); String[] SIPs= ipsection.substring (0, IDX). split ("\ \")); String[] Sipe= ipsection.substring (idx + 1). split ("\ \")); String[] Sipt= Ip.split ("\ \.")); LongIPS = 0L, Ipe = 0L, IPT = 0L; for(inti = 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) { Longt =IPs; IPs=Ipe; Ipe=T; } returnIPs <= IPT && IPT <=Ipe; } Public Static voidMain (string[] args) {if(Ipisvalid ("127.0.0.1-127.0.0.1", "127.0.0.1") {System.out.println ("IP belongs to this network segment"); } Else{System.out.println ("IP does not belong to this network segment"); } }
Httpconnectionutil Tool class test how network connectivity and testing are part of a network segment