[Tool class for java]ping or scan port

Source: Internet
Author: User



import java.io.bufferedreader;import java.io.ioexception;import java.io.inputstreamreader; Import java.io.printstream;import java.net.inetsocketaddress;import java.net.socket;import  java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import  Java.util.list;import java.util.map;public class discovery { printstream out  = null;   public discovery () {  }  public discovery ( printstream out) { this.out = out; }/** *  Ping detection of the specified IP (array)  *   *  @param  ips ip Arrays         *  @return   Returns the format  ip: succeeded  */public linkedhashmap<string, boolean> ping (List<String>  ips)  {LinkedHashMap<String, Boolean> ret = new LinkedHashMap< String, boolean> (); map<string,  String> args = new hashmap<string, string> (); bufferedreader br = null;for  (string ip : ips)  {args.put ("IP",  ip ); String value = systoolkitconfigure.getvalue ("Ping.command",  args);//  get the operating environment of the JVM// Runtime r = runtime.getruntime ();//  Create a ping command process try {process p =  Runtime.getruntime (). exec (value); Stringbuilder sb = new stringbuilder (); String line = null;br = new bufferedreader (New inputstreamreader ( P.getinputstream ()));while  ((Line = br.readline ())  != null)  {sb.append (Line.trim ()); Sb.append (' \ n ');} Br.close (); Br = new bufferedreader (New inputstreamreader (P.geterrorstream ()));while  ( (Line = br.readline ())  != null)  {sb.append (Line.trim ()); Sb.append (' \ n ');} Br.close (); String os = systoolkitconfigure.getos ().toLowerCase ();if  ( -1 != os.indexof ("Windows"))  {int index = sb.tostring (). IndexOf ("packets: sent = 1, received = 1,"); Ret.put (ip, index !=  -1); if (null!=out)  {out.println (ip+ ":" + (index != -1)); Out.flush ();}}  else if  ( -1 != os.indexof ("Linux"))  {int index = sb.tostring (). IndexOf ("1 packets transmitted, 1 received"); Ret.put (ip, index != -1); if ( Null!=out)  {out.println (ip+ ":" + (index != -1)); Out.flush ();}}}  catch  (ioexception e)  {// todo auto-generated catch block// E.printstacktrace ();}  }return ret;} /** *  Ping detection  *  *  @param for machines with specified IP ranges for specified network segments  networkSection *              network Segment, example:192.168.2 *  @param   startip *             start IP, including this IP, value >0 *  @param  endIp *              end IP, including this IP, value <255 *  @return  ping probe results  */public linkedhashmap<string, boolean> ping (string networksection,int  STARTIP,&NBSP;INT&NBSP;ENDIP)  {List<String> ips = new ArrayList<String> () ;if  (startip <= 0 | |  endip >= 255)  {throw new illegalargumentexception ("StartIp<=0 or  endip>=255. "); for  (int i = startip; i <= endip; i++)  {// ips.add ( String.Format ("%s.%d",  networksection,i); Ips.add (networksection +  ".")  + i);} Return ping (IPS);} /** *  This method is equivalent to ping (networksection,1,254)  *  *  @param  networksection *   @return &NBSP;*/PUBLIC&NBSP;LINKEDHASHMAP&LT;STRING,&NBsp Boolean> ping (string networksection)  {return ping (networksection, 1, 254);} Public linkedhashmap<string, boolean> scanport (string networksection,//int  Startip, int endip, string port)  {//// throw new runtimeexception ();// Linkedhashmap<string, boolean> ret = new linkedhashmap<string, boolean > ();//list<integer> ports = new arraylist<integer> ();//List<String>  ips = new ArrayList<String> (;//if ) (startip <= 0 | |  endip >= 255)  {//throw new illegalargumentexception ("StartIp<=0 or  endip>=255. "); /}//for  (int i = startip; i <= endip; i++)  {//ips.add ( networksection +  "."  + i)//}//string[] ss = port.split (",");//for  (String&nbsP;S&NBSP;:&NBSP;SS)  {//if  ( -1 != s.indexof ('-'))  {//String[] range =  S.split ("-");//for  (Int i = integer.parseint (range[0]),  end = integer//. parseint (range[1]);  i <= end; i++)  {//ports.add (i);//}//} else {// Ports.add (Integer.parseint (s));//}//}//socket client = null;//for  (String ip :  ips)  {//for  (integer p : ports)  {//try {//client = new  socket ();//client.connect (New inetsocketaddress (ip, p),  300);//ret.put (ip, true);/}  catch  (Exception ex)  {//ret.put (ip, false);//} finally {//try {//if   (null != client)//client.close ();//} catch  (Exception ex)  {//}//}//}////}/ /return ret;//}//public void scanport (list<string> ips, string port,  Printstream out)  {//list<integer> ports = new arraylist<integer> ();////String[] ss =  port.split (",");//for  (STRING&NBSP;S&NBSP;:&NBSP;SS)  {//if  ( -1 != s.indexof ('-') ))  {//string[] range = s.split ("-");//for  (Int i = integer.parseint ( Range[0]),  end = integer//.parseint (range[1]);  i <= end; i++)  {// Ports.add (i);//}//} else {//ports.add (Integer.parseint (s));//}//}////socket client =  null;//for  (string ip : ips)  {//for  (integer p : ports)  {// Try {//client = new socket ();//client.connect (New inetsocketaddress (ip, p),  300)//// ret.add (ip+ ":" +p);//out.println (ip +  ":"  + p);//out.flush ();//}  catch  (Exception ex)  {//} finally {//try {//if  (null != client)// Client.close ();//} catch  (Exception ex)  {//}//}//}//}////out.close ();//}public list<string>  Scanport (String networksection,int startip, int endip, string port)  {List <String> ips = new ArrayList<String> (;if ) (startip <= 0  | |  endip >= 255)  {throw new illegalargumentexception ("StartIp<=0 or  endip>=255. "); for  (int i = startip; i <= endip; i++)  {ips.add (networkSection  +  "."  + i);} Return scanport (Ips,port);} Public list<string> scanport (List<string> ips, string port)  {List <String> ret = new ArrayList<String> (); List<integer> ports = new arraylist<integer> (); String[] ss = port.split (",");for  (STRING&NBSP;S&NBSP;:&NBSP;SS)  {if  ( -1 != &nBsp;s.indexof ('-'))  {string[] range = s.split ("-");for  (int i =  Integer.parseint (Range[0]),  end = integer.parseint (range[1]); i <= end;  i++)  {ports.add (i);}}  else {ports.add (Integer.parseint (s));}} socket client = null;for  (string ip : ips)  {for  (Integer p  : ports)  {try {client = new socket (); Client.connect (new  Inetsocketaddress (ip, p),  300) Ret.add (ip +  ":"  + p); if (null!=out) {out.println ( ip +  ":"  + p); Out.flush ();}}  catch  (Exception ex)  {//system.out.println (Ex.getmessage ());}  finally {try {if  (null != client) Client.close ();}  catch  (Exception ex)  {}}}}return ret;}}


Configuration scan

import java.util.enumeration;import java.util.map;import java.util.properties;import  java.util.resourcebundle;import java.util.set;import java.util.concurrent.executorservice;/** *   *  @author  shanl * */public class systoolkitconfigure implements  Runnable{private static final String default_configure =  "Systoolkit_ Default ";p rivate static string user_configure = " Systoolkit ";//private int  Scaninterval = 1000*60*5;private int scaninterval = 1000*5;private static  properties config = new properties (); boolean isservice = false;/**  *  profile with default file name  */public systoolkitconfigure () {}/** *  *  @param   userconfig  User Custom profile  */public systoolkitconfigure (string userconfig) {user_configure =  userconfig;} Public&nBsp;void run ()  {resourcebundle confres = resourcebundle.getbundle (default_configure); Enumeration<string> keys = confres.getkeys (); while (Keys.hasmoreelements ()) {String  Key = keys.nextelement (); String value = confres.getstring (key); if (Null!=value)  config.setproperty (key, value);} Properties sysprop = system.getproperties (); Config.putall (Sysprop); for (;;) {Try{confres = resourcebundle.getbundle (user_configure); Keys = confres.getkeys (); while ( Keys.hasmoreelements ()) {Config.setproperty (Keys.nextelement (),  confres.getstring (Keys.nextElement ()));}} catch (Exception ex) {}if (Isservice)  try{thread.sleep (ScanInterval);  }catch (Exception ex) {} Else break;}} /** *  thread mode start  *  @param  threadPool  thread pool container, can be null */public void  Start (Executorservice threadpool) {isservice = true; Thread t = new&nbSp Thread (This,this.getclass (). Getsimplename ()); if (Null==threadpool) {T.start ();} Else{threadpool.execute (t);}} Public void stop () {this.isservice = false;} /** *  Setting the configuration text scan interval  *  @param  interval */public void setscaninterval (int  interval) {this.scaninterval = interval;} /** *  the value from the configuration file  *  @param  key *  @return   If it is not found (or if there is no value for this key), return ""  */ Public static string getvalue (String key) {String os = getos (). ToLowerCase () ; string ret =  "", If ( -1!=os.indexof ("Windows")) {Ret = config.getproperty (key+ ". Windows" ,"");} Else if ( -1!=os.indexof ("Linux")) {Ret = config.getproperty (key+ ". Linux", "");} if ("". Equals (ret)) {Ret = config.getproperty (key,  "");} Return ret;} /** *  the value from the configuration file and replaces the format of ${args.key} with args.value *  @param  key  *  @param  args  Parameters  *  @return  */pUblic static string getvalue (String key,map<string,string> args) {String  Value = getvalue (key), if ("". Equals (Value.trim ()))  return  ""; Set<map.entry<string,string>>values = args.entryset (); for (map.entry<string,string>  i: values) {Value = value .replaceall ("\\${1}\\{{1}" +i.getkey () + "\\}{1}",  I.getvalue ());} Return value;} Public staticstring getos () {Return system.getproperty ("Os.name");}}


Systoolkit.properties

Test=default test.test.linux=linux test.test.windows=windows test.ping.command.linux=ping-c 1-s 8 ${ip} Ping.command.windows=ping-n 1-w 1-l 8 ${ip}


Port Scan Test

/** * Scan port */static void T2 () {new Systoolkitconfigure (). Run ();D iscovery d = new Discovery (System.out);//d.scanport (" 192.168.2 ", 1, 254," 22,23,80 "); list<string> ips = new arraylist<string> () Ips.add ("192.168.2.22"); Ips.add ("192.168.2.23"); Ips.add (" 192.168.2.54 "), Ips.add (" 192.168.2.55 ");d. Scanport (IPs," 22,23,80,100-200 ");}
[Email protected] ~]# Java-jar discovery.jar192.168.2.1 : 23192.168.2.1:80192.168.2.10:80192.168.2.23:22192.168.2.37:23192.168.2.54:22192.168.2.54:23192.168.2.56:80192.168.2.57:2 2192.168.2.57:23192.168.2.100:22192.168.2.107:22192.168.2.141:80192.168.2.154:22192.168.2.154:23192.168.2.182:22192.168.2 .183:22192.168.2.201:22


Ping probing test

/** * ping scan  */static void  T1 () {new systoolkitconfigure (). Run ();D iscovery d = new discovery (System.out); Map<string,boolean> ret = d.ping ("192.168.2");//system.out.println (ret); List<string> ips = new arraylist<string> (); Ips.add ("192.168.2.22"); Ips.add (" 192.168.2.23 "); Ips.add (" 192.168.2.54 "); Ips.add (" 192.168.2.55 "); ret = d.ping (IPs);} 
[Email protected] ~]# Java-jar discovery.jar192.168.2.1:true192.168.2.2:false192.168.2.3:false192.168.2.4: false192.168.2.5:false192.168.2.6:true192.168.2.7:false192.168.2.8:true192.168.2.9:false192.168.2.10: true192.168.2.11:true192.168.2.12:false192.168.2.13:false192.168.2.14:false192.168.2.15:false192.168.2.16: false192.168.2.17:false192.168.2.18:true192.168.2.19:false192.168.2.20:false192.168.2.21:false192.168.2.22: true192.168.2.23:true192.168.2.24:false192.168.2.25:true192.168.2.26:false192.168.2.27:true192.168.2.28: false192.168.2.29:false192.168.2.30:true192.168.2.31:false192.168.2.32:true192.168.2.33:false192.168.2.34: False192.168.2.35:false192.168.2.36:false192.168.2.37:true


[Tool class for java]ping or scan port

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.