Simple implementation of multi-threaded network detection programs
Author: Bischofia 2004-7-8
A simple network connection detection program is written for some time, the function is to detect the connection between the computer in a certain network segment. The little program is used to use it, but it is relatively simple, and there is no special function. Recently, I have seen problems with netizens in the 9CBS Forum, so I moved out of the program, I hope that I can bring some help to users who need.
The entire interface of the program is as follows:
Remarks:
Textbox: Used to enter a Class C network segment;
NumericUpdown: used to select the IP range within the network segment;
NumericUpdown3: The number of IP used to select a thread process.
One of the main classes of the entire program is a pingcommand class. If you want to use a socket implementation, you can refer to Mencius E chapter an article.
Using system;
Using system.diagnostics;
Namespace ZZ
{
///
/// pingcompleted event commission
///
Public Delegate Void PingCompletedHandler (Object Sender, Pingeventargs E);
///
A summary description of /// pingcommand.
///
Public class pingcommand
{
///
/// pingcompleted event
///
Public Event PingCompletedHandler PingCompleted;
PRIVATE STRING [] _IPS;
PRIVATE Process_P;
///
/// Constructor
///
///
Public pingcommand (String [] IPS)
{
THIS._IPS = IPS;
THIS._P = New process ();
THIS._P.StartInfo.useshellexecute = false;
THIS._P.StartInfo.RedirectStandardinput = true;
THIS._P.StartInfo.RedirectStandardOutput = true;
THIS._P.StartInfo.RedirectStandarderror = true;
THIS._P.StartInfo.createnowindow = True;
THIS._P.StartInfo.FileName = "cmd.exe";
}
///
/// Thread call mode
///
Public void Runpings ()
{
Ping (this._if);
}
///
// / Execute the ping command
///
///
Public void ping (String IP)
{
_P.Start ();
_P.Standardinput.writeline ("ping -n 1" ip);
_P.Standardinput.writeLine ("exit");
String strrst = _p.standardoutput.readtoend ();
_P.close ();
IF (Strrst.indexof ("(0% loss)")! = - 1)
Strrst = "Connect";
ELSE IF ("Request Timed Out.")! = - 1)
Strrst = "Timeout";
Else IF ("Destination Host Unreachable.")! = - 1) Strrst = "Unable to reach the host";
Else IF (STRST.INDEXOF ("Unknown Host")! = - 1)
Strrst = "Unable to resolve the host";
OnpingCompleted (this, new pingeventArgs); "NEW STRING [,]);
}
///
/// Event processing
///
///
///
Protected Virtual Void OnpingCompleted (Object Sender, PingeventArgs E)
{
IF (pingcompleted! = null)
PingCompleted (Sender, e);
}
///
// / Execute the ping command
///
///
Public void ping (String [] IPS)
{
FOREACH (String IP in IPS)
Ping (IP);
}
}
///
// Define the parameter class
///
Public Class PingeventArgs: Eventargs
{
Private string [,] _PINGRESULT;
///
/// Constructor
///
/// ping result
Public pingeventargs (string [,] pingResult)
{
THIS._PINGRESULT = pingResult;
}
///
/// ping result
///
Public string [,] pingResult
{
Get {returnid;}
}
}
}
The above Pingeventargs class is Eventargs inheritance class, which is used to transmit the results of the PING command. There is also the judgment of the previous public void ping (String IP) method is not complete, the calling shell command is "ping -n 1 ipaddress", which can be referred to related articles, there is a need to pay attention to defining a Process class member. Variables, instantiate in the constructor and then reuse, if you instantiate a Process class when you call the ping method, it will become very slow.
The other is the form class, with an arraylist to save the thread object, below is the main code:
Namespace ZZ
{
Public Class Formrain: System.Windows.Forms.form
{
// commission
Private delegate void updatelistViewHandler (String [,] pingResult);
Private arraylist threadAdArray; // Used to save threads
Private datetime starttime; // Detect start time
Private int hostcount; // ip quantity
......
//Constructor
Public Formmain ()
{
InitializationComponent ();
THIS.Labellocal.Text = "Local host:" Environment.machinename;
THIS.THREADARRAY = New ArrayList ();
}
/// Run button execution function to start network detection
Private Void ButtonPing_Click (Object Sender, System.Eventargs E)
{
THISTVIEW1.Items.clear ();
THIS.LABELTIME.TEXT = String.empty; int start = (int) this.NumericUpdownStart.Value;
INT end = (int) this.NumericUpdownend.Value;
THIS.HOSTCOUNT = End-start 1;
String Caddress = this.TextBox1.text.substring (0, this.textbox1.text.lastIndexof ("."));
ArrayList ipslist = new arraylist ();
For (Int i = start; i <= end; i )
{
Ipslist.add (String.Format (Caddress ". {0}", i));
}
String [] IPS = (String []) ipslist.toArray (TypeOf (String));
IF (IPS! = null && = dengthth> 0)
{
THIS.BUTTONPING.ENABLED = FALSE;
THIS.StartTime = datetime.now;
INT ArrayLENTH = (int) this.NumericUpdownMax.Value; // number of IP executed by thread
Int threadcount = (int) Math.floor (ips.length / arraylent; // calculate the number of threads, if 0, calculate the remainder
THIS.THREADARRAY.CLEAR ();
Thread pingthread = NULL;
String [] newips = NULL;
For (int i = 0; i { Newips = new string [arraylenth]; Array.copy (IPS, I * Arraylenth, Newips, 0, ArrayLENTH); PingCommand pingcommand = new pingcommand (new hand); Pingthread = New Thread (New Threadstart (pingcommand.runpings); Pingcommand.PingCompleted = new pingcompletedhandler (pingcommand_pingcompleted); THIS.THREADARRAY.ADD (pingthread); Pingthread.start (); } INT endcount = (ips.length% arraylent; // calculate the remainder IF (endcount> 0) { NewIPS = new string [endcount]; Array.copy (IPS, IPS.LENGTH-EndCount-1, Newips, 0, EndCount); PingCommand pingcommand = new pingcommand (new hand); Pingthread = New Thread (New Threadstart (pingcommand.runpings); Pingcommand.PingCompleted = new pingcompletedhandler (pingcommand_pingcompleted); THIS.THREADARRAY.ADD (pingthread); Pingthread.start (); } THIS.LabelthreadCount.text = "Thread number:" this.threadArray.count.tostring ();} } // Update information display, invoke asynchronous call Private void pingcommand_pingcompleted (Object Sender, PingeventArgs E) { This.listview1.beginInvoke (New UpdatelistViewHandler (MessageInfoshow), new object [] {e.PingResult}); } // Update listview Private void messageinfoshow (string [,] pingResult) { This.ListView1.Items.Insert (0, New String [] {pingResult [0,0], pingResult [0,1]}); IF (this.listview1.items.count == this.hostcount) { this.listview1.refresh (); TimeSpan TS = (Timespan) (Timespan) (Timespan); THIS.LABELTIME.TEXT = "Detection Time:" Ts.Totalseconds.toTString () "Second"; this.ButtonPing.enabled = true; } } //exit the program Private void buttonxit_click (Object Sender, System.EventArgs E) { Application.exit (); } } }//Namespaces Here I saw the output information of the thread. Thread ' There is a big string.