private void button1_Click(object sender, System.EventArgs e)
{
string strHostToPing = "";
bool   bLoop = false;
bool   bAddressResolve = false;
int    iBytes = 32;
uint   lngCount = 3;
uint   lngTimeout = 1000;// for(int c=0;c<=2;c++)
// {
//Do the ping
StreamReader sr = new StreamReader(
(System.IO.Stream)File.OpenRead("d:\\ip.txt"),
System.Text.Encoding.Default);
ArrayList arr = new ArrayList(); 
while(sr.Peek() > -1) 
{
arr.Add(sr.ReadLine());  //加入数组
}
// MessageBox.Show(arr.Count.ToString());
ArrayList arrs = new ArrayList();
for (int i=0;i<arr.Count;i++)
{
arrs.Clear ();
bj=false;
arrs.AddRange (arr[i].ToString().Split(','));
for( int k = 0;k< arrs.Count ;k++)
{
if(bj == false)
{
listBox1.Items.Add( arrs[k].ToString () );
listBox1.Refresh();
PingHost(arrs[k].ToString(), iBytes, lngCount, lngTimeout );
listBox1.Refresh();

}
else
{
break;
}


}
if(bj == false)
{
show2(arrs[0].ToString ());
listBox2.Refresh (); }
                    
}
}

void show(string str)
{ int i = listBox1.Items.Add(str);
listBox1.SetSelected(i, true); } void show2(string str2)
{
int j = listBox2.Items.Add(str2);
listBox2.SetSelected (j,true);
}

解决方案 »

  1.   

    public void PingHost(string strPingHost, int iPingBytes, uint lngPingCount, uint lngPingTimeout)
    {
    const int     MAX_PACKET_SIZE = 65535;
    //Declare the IPHostEntry 
    IPHostEntry   PingTarget, PingSource;
    int           iBytesReceived = 0;
    int           dwStart = 0, dwStop = 0;
    uint          iLoop = 0;
    bool          bContinuous = false; // Get the server endpoint
    try
    {
    PingTarget = Dns.GetHostByName(strPingHost);
    }
    catch(Exception)
    {
    listBox1.ForeColor = System.Drawing.Color.Red ;
    listBox1.Items.Add("Unkown host "+ strPingHost +"");
    show( "Unkown host "+ strPingHost +" "); // fail
    return;
    } // Convert the server IP_EndPoint to an EndPoint
    IPEndPoint ipepServer = new IPEndPoint(PingTarget.AddressList[0],0);
    EndPoint epServer = (ipepServer); // Set the receiving endpoint to the client machine
    PingSource = Dns.GetHostByName(Dns.GetHostName());
    IPEndPoint ipEndPointFrom = new IPEndPoint(PingSource.AddressList[0],0);
    EndPoint   EndPointFrom = (ipEndPointFrom); int iPacketSize = 0;
    IcmpPacket PingPacket = new IcmpPacket();
    // Construct the packet to send
    PingPacket.Type = ICMP_ECHO; //8
    PingPacket.SubCode = 0;
    PingPacket.CheckSum = UInt16.Parse("0");
    PingPacket.Identifier   = UInt16.Parse("45");
    PingPacket.SequenceNumber  = UInt16.Parse("0");
    PingPacket.Data = new Byte[iPingBytes];
    //Initialize the Packet.Data
    for (int iCount = 0; iCount < iPingBytes; iCount++)
    {
    PingPacket.Data[iCount] = (byte)'#';
    } //Variable to hold the total Packet size
    iPacketSize = iPingBytes + 8;
    byte [] bytPktBuffer = new byte[iPacketSize];
    int iResult = 0; //Call a Method Serialize which counts
    //The total number of Bytes in the Packet
    iResult = Serialize(PingPacket, bytPktBuffer, iPacketSize, iPingBytes ); //Error in Packet Size
    if( iResult == -1 )
    {
    show( "Error in Making Packet");
    return;
    } /* now get this critter into a ushort array */
    ushort [] cksum_buffer = new ushort[Convert.ToInt32( Math.Ceiling( Convert.ToDouble(iResult) / 2))];
          
    //Code to initialize the ushort array 
    int icmp_header_buffer_index = 0;
    for( int iCount = 0; iCount < cksum_buffer.Length; iCount++ ) 
    {
    cksum_buffer[iCount] = BitConverter.ToUInt16(bytPktBuffer, icmp_header_buffer_index);
    icmp_header_buffer_index += 2;
    }
    //Call a method which will return a checksum
    //Save the checksum to the Packet
    PingPacket.CheckSum = CheckSum(cksum_buffer); // Now that we have the checksum, serialize the packet again
    byte [] byteSendBuffer = new byte[ iPacketSize ];
    //again check the PingPacket size
    iResult = Serialize(PingPacket, byteSendBuffer, iPacketSize, iPingBytes );
    //if there is a error report it
    if( iResult == -1 )
    {
    show("Error in Making Packet");
    return;
    } //listBox1.Items.add( "Pinging "+ strPingHost +" [" + ipepServer.Address.ToString() + "] with "+ iPingBytes +" bytes of data:\n" );
    //check for continuous
    if (lngPingCount == 0) bContinuous = true; //Loop the ping
    long lngPacketsSent = 0, lngPacketsReceived = 0, lngTotalTransmitTime = 0;
    int  iMinTransmitTime = int.MaxValue, iMaxTransmitTime = int.MinValue;
    do 
    {
    bool bReceived = false; //Initialize a Socket of the Type ICMP
    Socket PingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
    //Set socket timeout, but this doesn't seem to work...
    PingSocket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int) lngPingTimeout);
    PingSocket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.SendTimeout, (int) lngPingTimeout);
            
    // Initialize the buffers. The receive buffer is the size of the
    // ICMP header plus the IP header (20 bytes)
    byte [] ReceiveBuffer = new byte [MAX_PACKET_SIZE]; dwStart = System.Environment.TickCount; // Start timing
    //Gather stats
    lngPacketsSent ++;
    //send the Pack over the socket
    iResult = PingSocket.SendTo(byteSendBuffer, iPacketSize, SocketFlags.None , epServer);
    if ((iResult) == SOCKET_ERROR)
    {
    Console.WriteLine("Socket Error cannot Send Packet");
    }
    //Receive the bytes
    iBytesReceived = 0;
    //loop while waiting checking the time of the server responding 
    while(!bReceived)
    {
    try 
    {
    iBytesReceived = PingSocket.ReceiveFrom(ReceiveBuffer, MAX_PACKET_SIZE, SocketFlags.None, ref EndPointFrom);
    }
    catch //(Exception e)
    {
    //Console.WriteLine ("Request timed out. \n{0}", e.Message);
     //listBox1.ForeColor  = System.Drawing.Color.Red ;
    listBox1.Refresh();
    show( "Request timed out." );
    listBox1.Refresh();
    bReceived = false;
    break;
    }
    // if(iBytesReceived == 0)
    // {
    //                   show("error!");
    // }
    if (iBytesReceived == SOCKET_ERROR)
    {
    show("Host not Responding") ;
    bReceived = false;
    break;


    else if (iBytesReceived > 0) 
    {
    bReceived = true;
    dwStop = System.Environment.TickCount - dwStart; // stop timing //Check for timeout
    if ( dwStop > lngPingTimeout)
    {
    show("Request timed out.");
    bReceived = false;
    System.Threading.Thread.Sleep(System.TimeSpan.FromMilliseconds(1000));
    break;
    }
    if (dwStop < 10) 
    {
    show( "Reply from "+ ipepServer.Address.ToString() +": bytes: "+ Convert.ToString(iBytesReceived - 28) +" time:<10ms" );
    bj=true;
    listBox1.Refresh ();


    else 
    {
    show( "Reply from "+ ipepServer.Address.ToString() +": bytes: "+ Convert.ToString(iBytesReceived - 28) +" time: "+ dwStop +"ms" );
    listBox1.Refresh ();
    bj=true;
    }
    break;



    }//while //Gather stats
    if (bReceived) 
    {
    lngPacketsReceived++;
    lngTotalTransmitTime += dwStop;
    if (dwStop > iMaxTransmitTime) iMaxTransmitTime = dwStop;
    if (dwStop < iMinTransmitTime) iMinTransmitTime = dwStop;
    }
    iLoop++; if (bReceived & 
    (bContinuous | (iLoop < lngPingCount)))           //not last ping

    System.Threading.Thread.Sleep(System.TimeSpan.FromMilliseconds(1000));
    }
    //close the socket
    PingSocket.Shutdown(SocketShutdown.Both);
    PingSocket.Close();
    } while (bContinuous | (iLoop < lngPingCount));  //Do 
    //Report stats
    Console.WriteLine("\nPing statistics for {0}", ipepServer.Address.ToString());
    if (lngPacketsSent == 0) 
    {
    // Console.WriteLine("    Packets: Sent = {0}, Received = {1}, Lost = {2} ({3}% loss),", lngPacketsSent, lngPacketsReceived, lngPacketsSent-lngPacketsReceived, 0 );

    else
    {
    // Console.WriteLine("    Packets: Sent = {0}, Received = {1}, Lost = {2} ({3}% loss),", lngPacketsSent, lngPacketsReceived, lngPacketsSent-lngPacketsReceived, ((double) (lngPacketsSent-lngPacketsReceived)/lngPacketsSent)* 100 );
    }
    Console.WriteLine("Approximate round trip times in milli-seconds:");
    if (lngPacketsReceived == 0) 
    {
    // Console.WriteLine("    Minimum = {0}ms, Maximum =  {1}ms, Average =  {2}ms", 0, 0, 0 );

    else
    {
    // Console.WriteLine("    Minimum = {0}ms, Maximum =  {1}ms, Average =  {2}ms", iMinTransmitTime, iMaxTransmitTime,(int) ((double) (lngTotalTransmitTime/lngPacketsReceived)) );
    }
    return;
    }
      

  2.   

    public static int Serialize(IcmpPacket ThisPacket, byte[] Buffer, int PacketSize, int PingData )
    {
    int cbReturn = 0;
    // serialize the struct into the array
    int iIndex = 0; byte [] b_type = new byte[1];
    b_type[0] = ThisPacket.Type; byte [] b_code = new byte[1];
    b_code[0] = ThisPacket.SubCode; byte [] b_cksum = BitConverter.GetBytes(ThisPacket.CheckSum);
    byte [] b_id    = BitConverter.GetBytes(ThisPacket.Identifier);
    byte [] b_seq   = BitConverter.GetBytes(ThisPacket.SequenceNumber); // Console.WriteLine("Serialize type ");
    Array.Copy( b_type, 0, Buffer, iIndex, b_type.Length );
    iIndex += b_type.Length; // Console.WriteLine("Serialize code ");
    Array.Copy( b_code, 0, Buffer, iIndex, b_code.Length );
    iIndex += b_code.Length; // Console.WriteLine("Serialize cksum ");
    Array.Copy( b_cksum, 0, Buffer, iIndex, b_cksum.Length );
    iIndex += b_cksum.Length; // Console.WriteLine("Serialize id ");
    Array.Copy( b_id, 0, Buffer, iIndex, b_id.Length );
    iIndex += b_id.Length; Array.Copy( b_seq, 0, Buffer, iIndex, b_seq.Length );
    iIndex += b_seq.Length; // copy the data   
    Array.Copy( ThisPacket.Data, 0, Buffer, iIndex, PingData );
    iIndex += PingData;
    if( iIndex != PacketSize/* sizeof(IcmpPacket)  */) 
    {
    cbReturn = -1;
    return cbReturn;
    } cbReturn = iIndex;
    return cbReturn;
    }

    public static ushort CheckSum( ushort[] BufferToChecksum )
    {
    int iCheckSum = 0; for (uint iCount = 0; iCount < BufferToChecksum.Length; iCount++) 
    {
    iCheckSum += Convert.ToInt32( BufferToChecksum[iCount] );
    } iCheckSum = (iCheckSum >> 16) + (iCheckSum & 0xffff);
    iCheckSum += (iCheckSum >> 16);
    return (ushort)(~iCheckSum);
    } private void button2_Click(object sender, System.EventArgs e)
    {
    Application.Exit();
    } private void button3_Click(object sender, System.EventArgs e)
    {
    PingHost("134.41.119.2",32,6,100);
    } private void Form1_Load(object sender, System.EventArgs e)
    {

    } public class IcmpPacket
    {
    public byte     Type;             // type of message
    public byte     SubCode;          // type of sub code
    public ushort   CheckSum;         // ones complement checksum of struct
    public ushort   Identifier;       // identifier
    public ushort   SequenceNumber;   // sequence number  
    public byte[]   Data;             // byte array of data } }
    }
      

  3.   

    我自己写了一个程序是这样实现ping的。
    供楼主参考
    //调用ping命令,检测网络的连接状态
    public string Ping()
    {
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.CreateNoWindow = true;
    string pingrst = String.Empty;
    try
    {
    p.Start();
    p.StandardInput.WriteLine("ping -n 5 192.192.132.229");
    p.StandardInput.WriteLine("exit");
    string strRst = p.StandardOutput.ReadToEnd();

    if(strRst.IndexOf("(0% loss)")!=-1)
    {
    pingrst = "连接";
    }
    else
    {
    pingrst = "断开";
    }
        p.WaitForExit();
        p.Close();
    }
    catch
    {
    pingrst = "ping -n 3 "+ips[0] +"出错!";
    }
    return pingrst;
    }
      

  4.   

    修改
    //调用ping命令,检测网络的连接状态
    public string Ping(string ip)
    {
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.CreateNoWindow = true;
    string pingrst = String.Empty;
    try
    {
    p.Start();
    p.StandardInput.WriteLine("ping -n 5 "+ip);
    p.StandardInput.WriteLine("exit");
    string strRst = p.StandardOutput.ReadToEnd();

    if(strRst.IndexOf("(0% loss)")!=-1)
    {
    pingrst = "连接";
    }
    else
    {
    pingrst = "断开";
    }
        p.WaitForExit();
        p.Close();
    }
    catch
    {
    pingrst = "ping -n 5 "+ip +"出错!";
    }
    return pingrst;
    }
      

  5.   

    楼主参照下面的试试看
    using System;
    using System.Net;
    using System.Net.Sockets;namespace NetWorkPing
    {
    /// <summary>
    /// Ping 的摘要说明。
    /// </summary>
    public class Ping
    {
    //声明几个常量 
    const int SOCKET_ERROR = -1; 
    const int ICMP_ECHO = 8; 
    /// <summary> 
    /// 这里取得Hostname参数 
    /// </summary> 
    public static void Main(string[] argv) 

    if(argv.Length==0) 

    //If user did not enter any Parameter inform him 
    Console.WriteLine("Usage:Ping <hostname> /r") ; 
    Console.WriteLine("<hostname> The name of the Host who you want to ping"); 
    Console.WriteLine("/r Ping the host continuously") ; 

    else if(argv.Length==1) 

    //Just the hostname provided by the user 
    //call the method "PingHost" and pass the HostName as a parameter 
    PingHost(argv[0]) ; 

    else if(argv.Length==2) 

    //the user provided the hostname and the switch 
    if(argv[1]=="/r") 

    //loop the ping program 
    while(true) 

    //call the method "PingHost" and pass the HostName as a parameter 
    PingHost(argv[0]) ; 


    else 

    //if the user provided some other switch 
    PingHost(argv[0]) ; 


    else 

    //Some error occurred 
    Console.WriteLine("Error in Arguments") ; 

    }  /// <summary> 
    /// 主要的方法,用来取得IP, 
    /// 并计算响应时间 
    /// </summary> 
    public static void PingHost(string host) 

    //Declare the IPHostEntry 
    IPHostEntry serverHE, fromHE; 
    int nBytes = 0; 
    int dwStart = 0, dwStop = 0; 
    //Initilize a Socket of the Type ICMP 
    //Socket socket = new Socket(AddressFamily.AfINet, SocketType.SockRaw, ProtocolType.ProtICMP); 

    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
    // Get the server endpoint 
    try 

    serverHE = DNS.GetHostByName(host); 

    catch(Exception) 

    Console.WriteLine("Host not found"); // fail 
    return ; 
    }  // Convert the server IP_EndPoint to an EndPoint 
    IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0], 0); 
    EndPoint epServer = (ipepServer);  // Set the receiving endpoint to the client machine 
    fromHE = DNS.GetHostByName(DNS.GetHostName()); 
    IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0); 
    EndPoint EndPointFrom = (ipEndPointFrom);  int PacketSize = 0; 
    IcmpPacket packet = new IcmpPacket(); 
    // Construct the packet to send 
    packet.Type = ICMP_ECHO; //8 
    packet.SubCode = 0; 
    packet.CheckSum = UInt16.Parse("0"); 
    packet.Identifier = UInt16.Parse("45"); 
    packet.SequenceNumber = UInt16.Parse("0"); 
    int PingData = 32; // sizeof(IcmpPacket) - 8; 
    packet.Data = new Byte[PingData]; 
    //Initilize the Packet.Data 
    for (int i = 0; i < PingData; i++) 

    packet.Data[i] = (byte)'#'; 
    }  //Variable to hold the total Packet size 
    PacketSize = PingData + 8; 
    Byte [] icmp_pkt_buffer = new Byte[ PacketSize ]; 
    Int32 Index = 0; 
    //Call a Method Serialize which counts 
    //The total number of Bytes in the Packet 
    Index = Serialize(packet,icmp_pkt_buffer,PacketSize,PingData); 
    //Error in Packet Size 
    if( Index == -1 ) 

    Console.WriteLine("Error in Making Packet"); 
    return ; 
    }  // now get this critter into a UInt16 array  //Get the Half size of the Packet 
    Double double_length = Convert.ToDouble(Index); 
    Double dtemp = Math.Ceil( double_length / 2); 
    int cksum_buffer_length = Convert.ToInt32(dtemp); 
    //Create a Byte Array 
    UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length]; 
    //Code to initialize the Uint16 array 
    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; 

    //Call a method which will return a checksum 
    UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length); 
    //Save the checksum to the Packet 
    packet.CheckSum = u_cksum;  // Now that we have the checksum, serialize the packet again 
    Byte [] sendbuf = new Byte[ PacketSize ]; 
    //again check the packet size 
    Index = Serialize( 
    packet, 
    sendbuf, 
    PacketSize, 
    PingData ); 
    //if there is a error report it 
    if( Index == -1 ) 

    Console.WriteLine("Error in Making Packet"); 
    return ; 

    dwStart = System.Environment.TickCount; // Start timing 
    //send the Pack over the socket 
    if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR) 

    Console.WriteLine("Socket Error cannot Send Packet"); 

    // Initialize the buffers. The receive buffer is the size of the 
    // ICMP header plus the IP header (20 bytes) 
    Byte [] ReceiveBuffer = new Byte[256]; 
    nBytes = 0; 
    //Receive the bytes 
    bool recd =false ; 
    int timeout=0 ; 
      

  6.   


    //loop for checking the time of the server responding 
    while(!recd) 

    nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom); 
    if (nBytes == SOCKET_ERROR) 

    Console.WriteLine("Host not Responding") ; 
    recd=true ; 
    break; 

    else if(nBytes>0) 

    dwStop = System.Environment.TickCount - dwStart; // stop timing 
    Console.WriteLine("Reply from "+epServer.ToString()+" in " 
    +dwStop+"MS :Bytes Received"+nBytes); 
    recd=true; 
    break; 

    timeout=System.Environment.TickCount - dwStart; 
    if(timeout>1000) 

    Console.WriteLine("Time Out") ; 
    recd=true; 


    //close the socket 
    socket.Close(); 

    /// <summary> 
    /// This method get the Packet and calculates the total size 
    /// of the Pack by converting it to byte array 
    /// </summary> 
    public static Int32 Serialize(IcmpPacket packet, Byte[] Buffer, 
    Int32 PacketSize, Int32 PingData ) 

    Int32 cbReturn = 0; 
    // serialize the struct into the array 
    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);  // Console.WriteLine("Serialize type "); 
    Array.Copy( b_type, 0, Buffer, Index, b_type.Length ); 
    Index += b_type.Length;  // Console.WriteLine("Serialize code "); 
    Array.Copy( b_code, 0, Buffer, Index, b_code.Length ); 
    Index += b_code.Length;  // Console.WriteLine("Serialize cksum "); 
    Array.Copy( b_cksum, 0, Buffer, Index, b_cksum.Length ); 
    Index += b_cksum.Length;  // Console.WriteLine("Serialize id "); 
    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;  // copy the data 
    Array.Copy( packet.Data, 0, Buffer, Index, PingData ); 
    Index += PingData; 
    if( Index != PacketSize/* sizeof(IcmpPacket) */) 

    cbReturn = -1; 
    return cbReturn; 

    cbReturn = Index; 
    return cbReturn; 

    /// <summary> 
    /// This Method has the algorithm to make a checksum 
    /// </summary> 
    public static UInt16 checksum( UInt16[] buffer, int size ) 

    Int32 cksum = 0; 
    int counter; 
    counter = 0;  while ( size > 0 ) 

    UInt16 val = buffer[counter];  cksum += Convert.ToInt32( buffer[counter] ); 
    counter += 1; 
    size -= 1; 
    }  cksum = (cksum >> 16) + (cksum & 0xffff); 
    cksum += (cksum >> 16); 
    return (UInt16)(~cksum); 

    }
    // class ping 
    /// <summary> 
    /// Class that holds the Pack information 
    /// </summary> 
    public class IcmpPacket 

    public Byte Type; // type of message 
    public Byte SubCode; // type of sub code 
    public UInt16 CheckSum; // ones complement checksum of struct 
    public UInt16 Identifier; // identifier 
    public UInt16 SequenceNumber; // sequence number 
    public Byte [] Data; 
    }
    }
      

  7.   

    我下载的是ms开发的TreeView控件。我在vs.net集成开发环境中做了一个树结构,涉及到数据库,在后台添加结点,可就是在窗口不能显示,而直接操作TreeView的属性时能够显示。而我用一样的代码在dreamriver中开发时能够看到,请问这是为什么?我郁闷了好久,就是不能搞出来,而我又不想脱离vs.net去开发这个系统,请各位大哥帮帮忙,我不甚感激。是不是我的vs.net没有装好啊!一点没有显示!我不在集成开发环境里好好的啊!
      

  8.   

    to zhzuo(秋枫)    为什么我调试你的程序出现这样的问题。   E:\C#.net\ping--program\ping--program\Class1.cs(126): 'System.Math' does not contain a definition for 'Ceil'