zoukankan      html  css  js  c++  java
  • c# 下实现ping 命令操作

    1>通过.net提供的类实现

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 using System.Diagnostics;
     7 using System.Net.NetworkInformation;
     8 
     9 namespace ConsoleApplication1
    10 {
    11     class Program
    12     {
    13         static void Main(string[] args)
    14         {
    15             Ping ping = new Ping();
    16             Console.WriteLine(ping.Send("192.168.0.33").Status);
    17             Console.Read();
    18         }       
    19     }
    20 
    21 }

    2>同过调用cmd 的ping实现

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 using System.Diagnostics;
     7 using System.Net.NetworkInformation;
     8 
     9 namespace ConsoleApplication1
    10 {
    11     class Program
    12     {
    13         static void Main(string[] args)
    14         {
    15             Console.WriteLine(PingByProcess("192.168.0.33"));
    16             Console.Read();
    17         }
    18 
    19          static string PingByProcess(string ip)
    20         {
    21             using (Process p = new Process())
    22             {
    23                 p.StartInfo.FileName = "cmd.exe";
    24                 p.StartInfo.UseShellExecute = false;
    25                 p.StartInfo.RedirectStandardInput = true;
    26                 p.StartInfo.RedirectStandardOutput = true;
    27                 p.StartInfo.RedirectStandardError = true;
    28                 p.StartInfo.CreateNoWindow = true;
    29 
    30                 p.Start();
    31                 p.StandardInput.WriteLine(string.Format("ping -n 1 {0}", ip));
    32                 return p.StandardOutput.ReadToEnd();
    33             }
    34         }       
    35     }
    36 
    37 }

    3>利用原始Socket套接字,实现ICMP协议。

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Text;
      4 using System.Net;
      5 using System.Net.Sockets;
      6 
      7 
      8 public class PingHelp
      9 {
     10     const int SOCKET_ERROR = -1;
     11     const int ICMP_ECHO = 8;
     12 
     13     public string PingHost(string host)
     14     {
     15         // 声明 IPHostEntry 
     16         IPHostEntry ServerHE, fromHE;
     17         int nBytes = 0;
     18         int dwStart = 0, dwStop = 0;
     19 
     20         //初始化ICMP的Socket 
     21         Socket socket =
     22          new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
     23         socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000);
     24         // 得到Server EndPoint 
     25         try
     26         {
     27             ServerHE = Dns.GetHostByName(host);
     28         }
     29         catch (Exception)
     30         {
     31 
     32             return "没有发现主机";
     33         }
     34 
     35         // 把 Server IP_EndPoint转换成EndPoint 
     36         IPEndPoint ipepServer = new IPEndPoint(ServerHE.AddressList[0], 0);
     37         EndPoint epServer = (ipepServer);
     38 
     39         // 设定客户机的接收Endpoint 
     40         fromHE = Dns.GetHostByName(Dns.GetHostName());
     41         IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0);
     42         EndPoint EndPointFrom = (ipEndPointFrom);
     43 
     44         int PacketSize = 0;
     45         IcmpPacket packet = new IcmpPacket();
     46 
     47         // 构建要发送的包 
     48         packet.Type = ICMP_ECHO; //8 
     49         packet.SubCode = 0;
     50         packet.CheckSum = 0;
     51         packet.Identifier = 45;
     52         packet.SequenceNumber = 0;
     53         int PingData = 24; // sizeof(IcmpPacket) - 8; 
     54         packet.Data = new Byte[PingData];
     55 
     56         // 初始化Packet.Data 
     57         for (int i = 0; i < PingData; i++)
     58         {
     59             packet.Data[i] = (byte)'#';
     60         }
     61 
     62         //Variable to hold the total Packet size 
     63         PacketSize = 32;
     64         Byte[] icmp_pkt_buffer = new Byte[PacketSize];
     65         Int32 Index = 0;
     66         //again check the packet size 
     67         Index = Serialize(
     68          packet,
     69          icmp_pkt_buffer,
     70          PacketSize,
     71          PingData);
     72         //if there is a error report it 
     73         if (Index == -1)
     74         {
     75             return "Error Creating Packet";
     76 
     77         }
     78         // convert into a UInt16 array 
     79 
     80         //Get the Half size of the Packet 
     81         Double double_length = Convert.ToDouble(Index);
     82         Double dtemp = Math.Ceiling(double_length / 2);
     83         int cksum_buffer_length = Index / 2;
     84         //Create a Byte Array 
     85         UInt16[] cksum_buffer = new UInt16[cksum_buffer_length];
     86         //Code to initialize the Uint16 array 
     87         int icmp_header_buffer_index = 0;
     88         for (int i = 0; i < cksum_buffer_length; i++)
     89         {
     90             cksum_buffer[i] =
     91              BitConverter.ToUInt16(icmp_pkt_buffer, icmp_header_buffer_index);
     92             icmp_header_buffer_index += 2;
     93         }
     94         //Call a method which will return a checksum 
     95         UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length);
     96         //Save the checksum to the Packet 
     97         packet.CheckSum = u_cksum;
     98 
     99         // Now that we have the checksum, serialize the packet again 
    100         Byte[] sendbuf = new Byte[PacketSize];
    101         //again check the packet size 
    102         Index = Serialize(
    103          packet,
    104          sendbuf,
    105          PacketSize,
    106          PingData);
    107         //if there is a error report it 
    108         if (Index == -1)
    109         {
    110             return "Error Creating Packet";
    111 
    112         }
    113 
    114         dwStart = System.Environment.TickCount; // Start timing 
    115         //send the Packet over the socket 
    116         if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR)
    117         {
    118             return "Socket Error: cannot send Packet";
    119         }
    120         // Initialize the buffers. The receive buffer is the size of the 
    121         // ICMP header plus the IP header (20 bytes) 
    122         Byte[] ReceiveBuffer = new Byte[256];
    123         nBytes = 0;
    124         //Receive the bytes 
    125         bool recd = false;
    126         int timeout = 0;
    127 
    128         //loop for checking the time of the server responding 
    129         while (!recd)
    130         {
    131             nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom);
    132             if (nBytes == SOCKET_ERROR)
    133             {
    134                 return "主机没有响应";
    135 
    136             }
    137             else if (nBytes > 0)
    138             {
    139                 dwStop = System.Environment.TickCount - dwStart; // stop timing 
    140                 return "Reply from " + epServer.ToString() + " in "
    141                 + dwStop + "ms.  Received: " + nBytes + " Bytes.";
    142 
    143             }
    144             timeout = System.Environment.TickCount - dwStart;
    145             if (timeout > 1000)
    146             {
    147                 return "超时";
    148             }
    149         }
    150 
    151         //close the socket 
    152         socket.Close();
    153         return "";
    154     }
    155     /// <summary> 
    156     ///  This method get the Packet and calculates the total size 
    157     ///  of the Pack by converting it to byte array 
    158     /// </summary> 
    159     public static Int32 Serialize(IcmpPacket packet, Byte[] Buffer,
    160      Int32 PacketSize, Int32 PingData)
    161     {
    162         Int32 cbReturn = 0;
    163         // serialize the struct into the array 
    164         int Index = 0;
    165 
    166         Byte[] b_type = new Byte[1];
    167         b_type[0] = (packet.Type);
    168 
    169         Byte[] b_code = new Byte[1];
    170         b_code[0] = (packet.SubCode);
    171 
    172         Byte[] b_cksum = BitConverter.GetBytes(packet.CheckSum);
    173         Byte[] b_id = BitConverter.GetBytes(packet.Identifier);
    174         Byte[] b_seq = BitConverter.GetBytes(packet.SequenceNumber);
    175 
    176         Array.Copy(b_type, 0, Buffer, Index, b_type.Length);
    177         Index += b_type.Length;
    178 
    179         Array.Copy(b_code, 0, Buffer, Index, b_code.Length);
    180         Index += b_code.Length;
    181 
    182         Array.Copy(b_cksum, 0, Buffer, Index, b_cksum.Length);
    183         Index += b_cksum.Length;
    184 
    185         Array.Copy(b_id, 0, Buffer, Index, b_id.Length);
    186         Index += b_id.Length;
    187 
    188         Array.Copy(b_seq, 0, Buffer, Index, b_seq.Length);
    189         Index += b_seq.Length;
    190 
    191         // copy the data 
    192         Array.Copy(packet.Data, 0, Buffer, Index, PingData);
    193         Index += PingData;
    194         if (Index != PacketSize/* sizeof(IcmpPacket)  */)
    195         {
    196             cbReturn = -1;
    197             return cbReturn;
    198         }
    199 
    200         cbReturn = Index;
    201         return cbReturn;
    202     }
    203     /// <summary> 
    204     ///  This Method has the algorithm to make a checksum 
    205     /// </summary> 
    206     public static UInt16 checksum(UInt16[] buffer, int size)
    207     {
    208         Int32 cksum = 0;
    209         int counter;
    210         counter = 0;
    211 
    212         while (size > 0)
    213         {
    214             UInt16 val = buffer[counter];
    215 
    216             cksum += buffer[counter];
    217             counter += 1;
    218             size -= 1;
    219         }
    220 
    221         cksum = (cksum >> 16) + (cksum & 0xffff);
    222         cksum += (cksum >> 16);
    223         return (UInt16)(~cksum);
    224     }
    225 }
    226 /// 类结束 
    227 /// <summary> 
    228 ///  Class that holds the Pack information 
    229 /// </summary> 
    230 public class IcmpPacket
    231 {
    232     public Byte Type;    // type of message 
    233     public Byte SubCode;    // type of sub code 
    234     public UInt16 CheckSum;   // ones complement checksum of struct 
    235     public UInt16 Identifier;      // identifier 
    236     public UInt16 SequenceNumber;     // sequence number 
    237     public Byte[] Data;
    238 
    239 } // class IcmpPacket 
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Diagnostics;
    using System.Net.NetworkInformation;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                PingHelp p = new PingHelp();
                Console.WriteLine(p.PingHost("192.168.0.120"));
                Console.Read();
            }       
        }
    
    }

     程序员的基础教程:菜鸟程序员

  • 相关阅读:
    路飞学城Python-Day19
    路飞学城Python-Day18
    路飞学城Python-Day17
    ES6新特性概览
    关于Flex,有12个属性很重要
    Web前端工程师成长之路——知识汇总
    解决ajax跨域请求 (总结)
    项目中关于AJAX的使用总结
    Web前端性能优化——如何提高页面加载速度
    Canvas和SVG的区别
  • 原文地址:https://www.cnblogs.com/guohu/p/4601567.html
Copyright © 2011-2022 走看看