首页 > 开发 > 综合 > 正文

一段国外的PING程序(C#)

2024-07-21 02:27:07
字体:
来源:转载
供稿:网友

    //**************************************
    //    
    // name: ping .net class!
    // description:ping a machine from .net.
    //     this code is clr compliant.
    // by: carl mercier
    //
    // assumes:the code is a complete consol
    //     e application which can easilly modified
    //     to become windows form.
    //
    //this code is copyrighted and has    // limited warranties.please see http://
    //     www.planet-source-code.com/xq/asp/txtcod
    //     eid.335/lngwid.10/qx/vb/scripts/showcode
    //     .htm    //for details.    //**************************************
    //    
   
    using system;
    namespace myping
    {
    /// <summary>
    /// summary description for class1.
    /// </summary>
    class myping
    {
    /// <summary>
    /// the main entry point for the applica
    //     tion.
    /// </summary>
    //declare some constant variables
    const int socket_error = -1;
    const int icmp_echo = 8;
    [stathread]
    static void main(string[] args)
    {
    //
    // todo: add code to start application h
    //     ere
    //
    if(args.length==0)
    {
    //if user did not enter any parameter in
    //     form him
    console.writeline("usage:myping <hostname> /r") ;
    console.writeline("<hostname> the name of the host who you want to ping");
    console.writeline("/r optional switch to ping the host continuously") ;
    }
    else if(args.length==1)
    {
    //just the hostname provided by the user
    //    
    //call the method "pinghost" and pass th
    //     e hostname as a parameter
    pinghost(args[0]) ;
    }
    else if(args.length==2)
    {
    //the user provided the hostname and the
    //     switch
    if(args[1]=="/r")
    {
    //loop the ping program
    while(true)
    {
    //call the method "pinghost" and pass th
    //     e hostname as a parameter
    pinghost(args[0]) ;
    }
    }
    else
    {
    //if the user provided some other switch
    //    
    pinghost(args[0]) ;
    }
    }
    else
    {
    //some error occured
    console.writeline("error in arguments") ;
    }
    }
    public static void pinghost(string host)
    {
    //declare the iphostentry
    system.net.iphostentry serverhe, fromhe;
    int nbytes = 0;
    int dwstart = 0, dwstop = 0;
    //initilize a socket of the type icmp
    system.net.sockets.socket socket = new system.net.sockets.socket(system.net.sockets.addressfamily.internetwork,
    system.net.sockets.sockettype.raw, system.net.sockets.protocoltype.icmp);
    // get the server endpoint
    try
    {
    serverhe = system.net.dns.gethostbyname(host);
    }
    catch(exception)
    {
    console.writeline("host not found"); // fail
    return ;
    }
    // convert the server ip_endpoint to an
    //     endpoint
    system.net.ipendpoint ipepserver = new system.net.ipendpoint(serverhe.addresslist[0], 0);
    system.net.endpoint epserver = (ipepserver);
    // set the receiving endpoint to the cli
    //     ent machine
    fromhe = system.net.dns.gethostbyname(system.net.dns.gethostname());
    system.net.ipendpoint ipendpointfrom = new system.net.ipendpoint(fromhe.addresslist[0], 0);
    system.net.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 methos serialize which counts
    //the total number of bytes in the packe
    //     t
    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 ar
    //     ray
    //get the half size of the packet
    double double_length = convert.todouble(index);
    double dtemp = system.math.ceiling( double_length / 2);
    int cksum_buffer_length = convert.toint32(dtemp);
    //create a byte array
    uint16 [] cksum_buffer = new uint16[cksum_buffer_length];
    //code to initilize 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 chec
    //     ksum
    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, serial
    //     ize 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 b
    //     uffer is the size of the
    // icmp header plus the ip header (20 by
    //     tes)
    byte [] receivebuffer = new byte[256];
    nbytes = 0;
    //receive the bytes
    bool recd =false ;
    int timeout=0 ;
    //loop for checking the time of the serv
    //     er 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();
    }
    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;
    }
    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);
    }
    }
    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;
    }
    }
注册会员,创建你的web开发资料库,
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表