class Ping
{
const int SOCKET_ERROR = -1;
const int ICMP_ECHO = 8;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] arvs)
{
string[] args = new string[1];
args[0] = "192.168.1.154";
if(args.Length == 0)
{
System.Console.WriteLine("用法:Ping <hostname> /r");
System.Console.WriteLine("<hostname> 你要测试的远程主机");
System.Console.WriteLine("/r 选项开关,如果要连续测试时使用"); }
else if(args.Length == 1)
{
PingHost(args[0]);
System.Console.ReadLine(); }
else if(args.Length == 2)
{
if(args[1] == "/r")
{
while(true)
{
PingHost(args[0]);
}
}
else
{
PingHost(args[0]);
}
}
else
{
System.Console.WriteLine("Error in Arguments");
}
}
public static UInt16 checksum(UInt16[] buffer,int size)
{
Int32 cksum = 0;
int counter = 0;
while (size>0)
{
UInt16 val = buffer[counter];
cksum += Convert.ToInt32(buffer[counter]);
counter++;
size--;
} cksum = (cksum >> 16)+(cksum & 0xffff);
cksum += (cksum >> 16);
return (UInt16)(~cksum); }
public static Int32 Serialize( IcmpPacket packet,Byte[] Buffer,Int32 PacketSize,Int32 PingData)
{
Int32 cbReturn = 0;
int Index = 0;
Byte[] b_type = new Byte[1];
b_type[0] = (packet.Type); Byte[] b_code = new Byte[1];
b_code[0] = (packet.SubCode); Byte[] b_cksum = BitConverter.GetBytes(packet.CheckSum);
Byte[] b_id = BitConverter.GetBytes(packet.Identifier);
Byte[] b_seq = BitConverter.GetBytes(packet.SequenceNumber); Array.Copy(b_type,0,Buffer,Index,b_type.Length);
Index += b_type.Length; Array.Copy(b_code,0,Buffer,Index,b_code.Length);
Index += b_code.Length; Array.Copy(b_cksum,0,Buffer,Index,b_cksum.Length);
Index += b_cksum.Length; Array.Copy(b_id,0,Buffer,Index,b_id.Length);
Index += b_id.Length; Array.Copy(b_seq,0,Buffer,Index,b_seq.Length);
Index += b_seq.Length; Array.Copy(packet.Data,0,Buffer,Index,PingData);
Index += PingData; if(Index != PacketSize)
{
cbReturn = -1;
return cbReturn;
}
cbReturn = Index;
return cbReturn;
}
public static void PingHost(string host)
{
IPHostEntry serverHE,fromHE;
int nBytes = 0;
int dwStart = 0;
int dwStop = 0; Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp); try
{
serverHE = Dns.GetHostByName(host);
}
catch(Exception)
{
System.Console.WriteLine("目标主机不存在");
return;
} IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0],0);
EndPoint epServer = (ipepServer); fromHE = Dns.GetHostByName(Dns.GetHostName());
IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0],0);
EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = 0;
IcmpPacket packet = new IcmpPacket(); packet.Type = ICMP_ECHO;
packet.SubCode = 0;
packet.CheckSum = UInt16.Parse("0");
packet.Identifier = UInt16.Parse("45");
packet.SequenceNumber = UInt16.Parse("0"); int PingData = 32;
packet.Data = new Byte[PingData]; for(int i=0;i<PingData;i++)
{
packet.Data[i] = (byte)'#';
} PacketSize = PingData + 8; Byte[] icmp_pkt_buffer = new Byte[PacketSize]; Int32 Index = 0; Index = Serialize(packet,icmp_pkt_buffer,PacketSize,PingData); if(Index == -1)
{
System.Console.WriteLine("Error in Making Packet");
return;
} Double double_length = Convert.ToDouble(Index);
Double dtemp = Math.Ceiling(double_length/2);
int cksum_buffer_length = Convert.ToInt32(dtemp); UInt16[] cksum_buffer = new UInt16[cksum_buffer_length]; int icmp_header_buffer_index = 0;
for(int i=0;i<cksum_buffer_length;i++)
{
cksum_buffer[i] = BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);
icmp_header_buffer_index += 2;
} UInt16 u_cksum = checksum(cksum_buffer,cksum_buffer_length); packet.CheckSum = u_cksum; Byte[] sendbuf = new Byte[PacketSize];
Index = Serialize(packet,sendbuf,PacketSize,PingData); if(Index == -1)
{
System.Console.WriteLine("Error in Making Packet");
return;
} dwStart = System.Environment.TickCount; if((nBytes = socket.SendTo(sendbuf,PacketSize,0,epServer)) == SOCKET_ERROR)
{
System.Console.WriteLine("Socket Error can not Sending Packet");
} Byte[] ReceiveBuffer = new Byte[256];
nBytes = 0; bool recd = false;
int timeout = 0; while(!recd)
{
nBytes = socket.ReceiveFrom(ReceiveBuffer,256,0,ref EndPointFrom);
if(nBytes == SOCKET_ERROR)
{
System.Console.WriteLine("Host not Responding");
recd = true;
break;
}
else if(nBytes > 0)
{
dwStop = System.Environment.TickCount - dwStart;
Console.WriteLine("Reply from"+epServer.ToString()+":bytes = "+ nBytes.ToString()+"time = "+dwStop +"ms");
recd = true;
break;
} timeout = System.Environment.TickCount - dwStart;
if(timeout > 1000)
{
System.Console.WriteLine("Time Out");
recd = true;
}
}
socket.Close();
} }public class IcmpPacket
{
public IcmpPacket()
{
//
// TODO: 在此处添加构造函数逻辑
//
} public Byte Type;
public Byte SubCode;
public UInt16 CheckSum;
public UInt16 Identifier;
public UInt16 SequenceNumber;
public Byte[] Data;
}自己写返回值
{
const int SOCKET_ERROR = -1;
const int ICMP_ECHO = 8;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] arvs)
{
string[] args = new string[1];
args[0] = "192.168.1.154";
if(args.Length == 0)
{
System.Console.WriteLine("用法:Ping <hostname> /r");
System.Console.WriteLine("<hostname> 你要测试的远程主机");
System.Console.WriteLine("/r 选项开关,如果要连续测试时使用"); }
else if(args.Length == 1)
{
PingHost(args[0]);
System.Console.ReadLine(); }
else if(args.Length == 2)
{
if(args[1] == "/r")
{
while(true)
{
PingHost(args[0]);
}
}
else
{
PingHost(args[0]);
}
}
else
{
System.Console.WriteLine("Error in Arguments");
}
}
public static UInt16 checksum(UInt16[] buffer,int size)
{
Int32 cksum = 0;
int counter = 0;
while (size>0)
{
UInt16 val = buffer[counter];
cksum += Convert.ToInt32(buffer[counter]);
counter++;
size--;
} cksum = (cksum >> 16)+(cksum & 0xffff);
cksum += (cksum >> 16);
return (UInt16)(~cksum); }
public static Int32 Serialize( IcmpPacket packet,Byte[] Buffer,Int32 PacketSize,Int32 PingData)
{
Int32 cbReturn = 0;
int Index = 0;
Byte[] b_type = new Byte[1];
b_type[0] = (packet.Type); Byte[] b_code = new Byte[1];
b_code[0] = (packet.SubCode); Byte[] b_cksum = BitConverter.GetBytes(packet.CheckSum);
Byte[] b_id = BitConverter.GetBytes(packet.Identifier);
Byte[] b_seq = BitConverter.GetBytes(packet.SequenceNumber); Array.Copy(b_type,0,Buffer,Index,b_type.Length);
Index += b_type.Length; Array.Copy(b_code,0,Buffer,Index,b_code.Length);
Index += b_code.Length; Array.Copy(b_cksum,0,Buffer,Index,b_cksum.Length);
Index += b_cksum.Length; Array.Copy(b_id,0,Buffer,Index,b_id.Length);
Index += b_id.Length; Array.Copy(b_seq,0,Buffer,Index,b_seq.Length);
Index += b_seq.Length; Array.Copy(packet.Data,0,Buffer,Index,PingData);
Index += PingData; if(Index != PacketSize)
{
cbReturn = -1;
return cbReturn;
}
cbReturn = Index;
return cbReturn;
}
public static void PingHost(string host)
{
IPHostEntry serverHE,fromHE;
int nBytes = 0;
int dwStart = 0;
int dwStop = 0; Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp); try
{
serverHE = Dns.GetHostByName(host);
}
catch(Exception)
{
System.Console.WriteLine("目标主机不存在");
return;
} IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0],0);
EndPoint epServer = (ipepServer); fromHE = Dns.GetHostByName(Dns.GetHostName());
IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0],0);
EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = 0;
IcmpPacket packet = new IcmpPacket(); packet.Type = ICMP_ECHO;
packet.SubCode = 0;
packet.CheckSum = UInt16.Parse("0");
packet.Identifier = UInt16.Parse("45");
packet.SequenceNumber = UInt16.Parse("0"); int PingData = 32;
packet.Data = new Byte[PingData]; for(int i=0;i<PingData;i++)
{
packet.Data[i] = (byte)'#';
} PacketSize = PingData + 8; Byte[] icmp_pkt_buffer = new Byte[PacketSize]; Int32 Index = 0; Index = Serialize(packet,icmp_pkt_buffer,PacketSize,PingData); if(Index == -1)
{
System.Console.WriteLine("Error in Making Packet");
return;
} Double double_length = Convert.ToDouble(Index);
Double dtemp = Math.Ceiling(double_length/2);
int cksum_buffer_length = Convert.ToInt32(dtemp); UInt16[] cksum_buffer = new UInt16[cksum_buffer_length]; int icmp_header_buffer_index = 0;
for(int i=0;i<cksum_buffer_length;i++)
{
cksum_buffer[i] = BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);
icmp_header_buffer_index += 2;
} UInt16 u_cksum = checksum(cksum_buffer,cksum_buffer_length); packet.CheckSum = u_cksum; Byte[] sendbuf = new Byte[PacketSize];
Index = Serialize(packet,sendbuf,PacketSize,PingData); if(Index == -1)
{
System.Console.WriteLine("Error in Making Packet");
return;
} dwStart = System.Environment.TickCount; if((nBytes = socket.SendTo(sendbuf,PacketSize,0,epServer)) == SOCKET_ERROR)
{
System.Console.WriteLine("Socket Error can not Sending Packet");
} Byte[] ReceiveBuffer = new Byte[256];
nBytes = 0; bool recd = false;
int timeout = 0; while(!recd)
{
nBytes = socket.ReceiveFrom(ReceiveBuffer,256,0,ref EndPointFrom);
if(nBytes == SOCKET_ERROR)
{
System.Console.WriteLine("Host not Responding");
recd = true;
break;
}
else if(nBytes > 0)
{
dwStop = System.Environment.TickCount - dwStart;
Console.WriteLine("Reply from"+epServer.ToString()+":bytes = "+ nBytes.ToString()+"time = "+dwStop +"ms");
recd = true;
break;
} timeout = System.Environment.TickCount - dwStart;
if(timeout > 1000)
{
System.Console.WriteLine("Time Out");
recd = true;
}
}
socket.Close();
} }public class IcmpPacket
{
public IcmpPacket()
{
//
// TODO: 在此处添加构造函数逻辑
//
} public Byte Type;
public Byte SubCode;
public UInt16 CheckSum;
public UInt16 Identifier;
public UInt16 SequenceNumber;
public Byte[] Data;
}自己写返回值
解决方案 »
- 请问一个c#中怎么使用别名呀?
- new 一个带有 main()入口函数的类为什么不会引起混乱?
- 100分color 转换为 int,int 转化为 color如何实现?
- 请高人解释:关于串口的一些函数
- 求一句SQL
- 请问,存储过程中怎么判断输入参数是否等于某个值?
- 急~~~~!!!!VS2005里的水晶报表改怎么用 哪里有教程?
- 在XP下与pocket pc的连接问题
- 极度郁闷中,,,,,,,,高人进来~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 请问C#中调用udl文件是不是只有使用streamreader对象一个方式
- 求救一条SQL查询语句
- 用C#写了一个winform的多线程ping程序,欢迎大家测试
Imports System.Net
Imports System.Net.SocketsPublic Class pinghost Public Structure stcError
Dim Number As Integer
Dim Description As String
End Structure Public Enum Options
SUCCESS = 0
ERR = (-1)
ERR_HOST_NOT_FOUND = PING_ERROR_BASE + 1
ERR_SOCKET_DIDNT_SEND = PING_ERROR_BASE + 2
ERR_HOST_NOT_RESPONDING = PING_ERROR_BASE + 3
ERR_TIME_OUT = PING_ERROR_BASE + 4
End Enum#Region "declare" Private Const PING_ERROR_BASE As Long = &H8000 Private Const ICMP_ECHO As Integer = 8
Private Const SOCKET_ERROR As Integer = -1 Private udtError As stcError Private Const intPortICMP As Integer = 7
Private Const intBufferHeaderSize As Integer = 8
Private Const intPackageHeaderSize As Integer = 28 Private byteDataSize As Byte
Private lngTimeOut As Long
Private ipheLocalHost As System.Net.IPHostEntry
Private ipheHost As System.Net.IPHostEntry Public Property TimeOut() As Long
Get
Return lngTimeOut
End Get
Set(ByVal Value As Long)
lngTimeOut = Value
End Set
End Property Public Property DataSize() As Byte
Get
Return byteDataSize
End Get
Set(ByVal Value As Byte)
byteDataSize = Value
End Set
End Property Private ReadOnly Property Identifier() As Byte
Get
Return 0
End Get
End Property Private ReadOnly Property Sequence() As Byte
Get
Return 0
End Get
End Property Private ReadOnly Property LocalHost() As System.Net.IPHostEntry
Get
Return ipheLocalHost
End Get
End Property Public Property Host() As Object
Get
Return ipheHost
End Get
Set(ByVal Value As Object)
If (Value.GetType.ToString.ToLower = "system.string") Then
Try
ipheHost = System.Net.Dns.GetHostByName(Value)
Catch
ipheHost = Nothing
udtError.Number = Options.ERR_HOST_NOT_FOUND
udtError.Description = "Host " & ipheHost.HostName & " not found."
End Try
ElseIf (Value.GetType.ToString.ToLower = "system.net.iphostentry") Then
ipheHost = (Value)
Else
ipheHost = Nothing
End If
End Set
End Property#End Region Public Sub New()
byteDataSize = 32
lngTimeOut = 500
udtError = New stcError
ipheLocalHost = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName())
ipheHost = Nothing
End Sub Public Function Ping() As Long Dim intCount As Integer
Dim aReplyBuffer(255) As Byte Dim intNBytes As Integer = 0 Dim intEnd As Integer
Dim intStart As Integer Dim epFrom As System.Net.EndPoint
Dim epServer As System.Net.EndPoint
Dim ipepServer As System.Net.IPEndPoint ipepServer = New System.Net.IPEndPoint(ipheHost.AddressList(0), 0)
epServer = CType(ipepServer, System.Net.EndPoint) epFrom = New System.Net.IPEndPoint(ipheLocalHost.AddressList(0), 0) DataSize = Convert.ToByte(DataSize + intBufferHeaderSize) If (DataSize Mod 2 = 1) Then
DataSize += Convert.ToByte(1)
End If
Dim aRequestBuffer(DataSize - 1) As Byte aRequestBuffer(0) = Convert.ToByte(8) ' ECHO Request BitConverter.GetBytes(Identifier).CopyTo(aRequestBuffer, 4) BitConverter.GetBytes(Sequence).CopyTo(aRequestBuffer, 6) Dim i As Integer
For i = 8 To DataSize - 1
aRequestBuffer(i) = Convert.ToByte(i Mod 8)
Next i Call CreateChecksum(aRequestBuffer, DataSize, aRequestBuffer(2), aRequestBuffer(3)) Try
Dim sckSocket As New System.Net.Sockets.Socket( _
Net.Sockets.AddressFamily.InterNetwork, _
Net.Sockets.SocketType.Raw, _
Net.Sockets.ProtocolType.Icmp)
sckSocket.Blocking = False sckSocket.SendTo(aRequestBuffer, 0, DataSize, SocketFlags.None, ipepServer) intStart = System.Environment.TickCount Do
Application.DoEvents()
Try
intNBytes = sckSocket.ReceiveFrom(aReplyBuffer, SocketFlags.None, epServer)
Catch objErr As Exception
End Try
Loop Until (intNBytes > 0) Or ((System.Environment.TickCount - intStart) > TimeOut) If ((System.Environment.TickCount - intStart) > TimeOut) Then
udtError.Number = Options.ERR_TIME_OUT
udtError.Description = "Time Out"
Return (Options.ERR)
End If intEnd = System.Environment.TickCount If (intNBytes > 0) Then
udtError.Number = (aReplyBuffer(19) * &H100) + aReplyBuffer(20)
Select Case aReplyBuffer(20)
Case 0 : udtError.Description = "Success"
Case 1 : udtError.Description = "Buffer too Small"
Case 2 : udtError.Description = "Destination Unreahable"
Case 3 : udtError.Description = "Dest Host Not Reachable"
Case 4 : udtError.Description = "Dest Protocol Not Reachable"
Case 5 : udtError.Description = "Dest Port Not Reachable"
Case 6 : udtError.Description = "No Resources Available"
Case 7 : udtError.Description = "Bad Option"
Case 8 : udtError.Description = "Hardware Error"
Case 9 : udtError.Description = "Packet too Big"
Case 10 : udtError.Description = "Reqested Timed Out"
Case 11 : udtError.Description = "Bad Request"
Case 12 : udtError.Description = "Bad Route"
Case 13 : udtError.Description = "TTL Exprd In Transit"
Case 14 : udtError.Description = "TTL Exprd Reassemb"
Case 15 : udtError.Description = "Parameter Problem"
Case 16 : udtError.Description = "Source Quench"
Case 17 : udtError.Description = "Option too Big"
Case 18 : udtError.Description = "Bad Destination"
Case 19 : udtError.Description = "Address Deleted"
Case 20 : udtError.Description = "Spec MTU Change"
Case 21 : udtError.Description = "MTU Change"
Case 22 : udtError.Description = "Unload"
Case Else : udtError.Description = "General Failure"
End Select
End If
Return (intEnd - intStart)
Catch oExcept As Exception
End Try End Function Public Function GetLastError() As stcError
Return udtError
End Function Private Sub CreateChecksum(ByRef data() As Byte, ByVal Size As Integer, ByRef HiByte As Byte, ByRef LoByte As Byte)
Dim i As Integer
Dim chk As Integer = 0 For i = 0 To Size - 1 Step 2
chk += Convert.ToInt32(data(i) * &H100 + data(i + 1))
Next chk = Convert.ToInt32((chk And &HFFFF&) + Fix(chk / &H10000&))
chk += Convert.ToInt32(Fix(chk / &H10000&))
chk = Not (chk) HiByte = Convert.ToByte((chk And &HFF00) / &H100)
LoByte = Convert.ToByte(chk And &HFF)
End SubEnd Class
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
namespace NET_SCAN
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.NumericUpDown numericUpDown2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.NumericUpDown numericUpDown3;
private System.Windows.Forms.Label label4;
//delegate
private delegate void updatelistview(string [,] a);
private delegate void updatelabel(int i); private int box;
private Thread [] pingthread;
private int j;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null; public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent(); this.button1.Focus();
this.listView1.View=System.Windows.Forms.View.Details;
ColumnHeader a=new ColumnHeader();
ColumnHeader c=new ColumnHeader(); a.Text=" 主 机 IP 地 址 ";
a.Width=200;
a.TextAlign=System.Windows.Forms.HorizontalAlignment.Left;
c.Text="连 接 状 态";
c.Width=120;
c.TextAlign=System.Windows.Forms.HorizontalAlignment.Left; this.listView1.Columns.Add(a);
this.listView1.Columns.Add(c);
this.label4.Visible=false;
this.label5.Visible=false;
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void button2_Click(object sender, System.EventArgs e)
{
this.Closing -= new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
thread_clear();
this.Close();
} private void Form1_Load(object sender, System.EventArgs e)
{
this.textBox1.Text="192.168.0.0";
this.textBox2.Text="本地主机:"+System.Environment.MachineName;
this.numericUpDown1.Minimum=1;
this.numericUpDown1.Maximum=254;
this.numericUpDown2.Minimum=1;
this.numericUpDown2.Maximum=254;
this.numericUpDown2.Value=254;
}
private void button1_Click(object sender, System.EventArgs e)
{
this.Cursor=System.Windows.Forms.Cursors.WaitCursor;
this.label5.Visible=true;
int start=(int)this.numericUpDown1.Value;
int end=(int)this.numericUpDown2.Value;
box=end-start+1;
string s1=this.textBox1.Text.Trim().Substring(0,this.textBox1.Text.LastIndexOf("."));
ArrayList s2=new ArrayList();
for(int i=start;i<=end;i++)
{
s2.Add(string.Format(s1+".{0}",i));
}
string []s3=(string [])s2.ToArray(typeof(string));//复制数据
if(s3.Length>0)
{
this.button1.Enabled=false;
int ipcount=(int)this.numericUpDown3.Value;//一个线程执行的ip数
int threadcount=(int)Math.Floor(s3.Length/ipcount);//计算线程数量
string []s4=null;
j=threadcount+1;
pingthread=new Thread[j];
for(int i=0;i<threadcount;i++)
{
System.Windows.Forms.Application.DoEvents();
s4=new string[ipcount];
Array.Copy(s3,i*ipcount,s4,0,ipcount);
pingcmd myping=new pingcmd(s4);
pingthread[i]=new Thread(new ThreadStart(myping.runping));
myping.pingcom+=new pingcmd_completed(listview_refresh);
pingthread[i].Start();
}
this.label4.Text="线程数量为: "+threadcount.ToString();
int endcount=s3.Length%ipcount;
if(endcount>0)
{
s4=new string[endcount];
Array.Copy(s3,s3.Length-endcount-1,s4,0,endcount);
pingcmd myping=new pingcmd(s4);
pingthread[j-1]=new Thread(new ThreadStart(myping.runping));
myping.pingcom+=new pingcmd_completed(listview_refresh);
pingthread[j-1].Start();
this.label4.Text="线程数量为: "+(threadcount+1).ToString();
this.label4.Visible=true;
}
}//if
} private void Form1_Activated(object sender, System.EventArgs e)
{ this.label5.Focus();
}
private void listview_refresh(object sender,PingEventArgs e)
{
this.listView1.BeginInvoke(new updatelistview(dowork),new object []{e.ping_result});
} private void dowork(string [,] b)
{
this.listView1.Items.Add(new ListViewItem(new string[]{b[0,0],b[0,1]}));
this.listView1.Refresh();
this.label5.BeginInvoke(new updatelabel(this.dowork2),new object[]{this.listView1.Items.Count});
} private void dowork2(int i)
{
this.label5.Text="已扫描了"+i.ToString()+"台计算机,请稍等..";
if(i>=box)
{
this.label5.Visible=false;
thread_clear();
this.Cursor=System.Windows.Forms.Cursors.Default;
}
}
private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.label5.Focus();
} private void listView1_Click(object sender, System.EventArgs e)
{
this.label5.Focus();
} private void listView1_MouseEnter(object sender, System.EventArgs e)
{
this.label5.Focus();
} private void thread_clear()
{
for(int k=0;k<j-1;k++)
{
if(pingthread[k].IsAlive && pingthread[k]!=null)
{
pingthread[k].Abort();
pingthread[k]=null; }
System.Windows.Forms.Application.DoEvents();
}
} private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
int i=sender.GetType().ToString().Trim().LastIndexOf(".")+1;
string a=sender.GetType().ToString();
a=a.Substring(i,4);
if(a.Equals("Form"))
e.Cancel=true;
}
}
}
using System.Diagnostics;namespace NET_SCAN
{
public delegate void pingcmd_completed(object sender,PingEventArgs e);
public class pingcmd
{
private Process myp; public event pingcmd_completed pingcom;//发布事件
private string [] s;
public pingcmd(string [] a) //构造函数
{
//
// TODO: 在此处添加构造函数逻辑
//
this.s=a;
myp=new Process();
myp.StartInfo.UseShellExecute=false;
myp.StartInfo.RedirectStandardError=true;
myp.StartInfo.RedirectStandardInput=true;
myp.StartInfo.RedirectStandardOutput=true;
myp.StartInfo.CreateNoWindow=true;
myp.StartInfo.FileName="cmd.exe";
} public void runping()//线程调用方法
{
ping(this.s);
} public void ping(string ip)//执行ping方法
{
myp.Start();
myp.StandardInput.WriteLine("ping -n 1 "+ip);
myp.StandardInput.WriteLine("exit");
string strRst=myp.StandardOutput.ReadToEnd();
string pingrst="";
myp.Close();
if(strRst.IndexOf("(0% loss)")!=-1)
pingrst = " 连 接 正 常 ";
else if( strRst.IndexOf("Destination host unreachable")!=-1)
pingrst = "无法到达目的主机";
else if(strRst.IndexOf("Request timed out")!=-1)
pingrst = " 连 接 超 时 ";
else if(strRst.IndexOf("Unknown host")!=-1)
pingrst = " 无法解析主机 ";
onpingcomplete(this,new PingEventArgs(new string[,] {{ip,pingrst}}));
} public void ping(string [] ips)
{
foreach(string ip in ips)
ping(ip); } protected virtual void onpingcomplete(object sender,PingEventArgs e)//虚方法
{
pingcom(sender,e);
} }//pingcmd类
////////////////////////
//参数类
/// //////////////
public class PingEventArgs :EventArgs
{
private string [,] pingresult;
public PingEventArgs(string [,] s)
{
this.pingresult=s; } //ping结果
public string [,] ping_result
{
get
{
return this.pingresult;
} } }
}
PingEventArgs --- 无法设计基类“System.EventArgs”。
[email protected]
谢谢!