日期:2014-05-18  浏览次数:20941 次

ping命令

  private void simpleBtn_Click(object sender, EventArgs e)
  {
  //如信息未填写完整,报错并退出
  if (hostTextBox.Text == "")
  {
  MessageBox.Show("IP地址不能为空!");
  }
  //初始化消息数据
  byte[] msgData=new byte[1024];
  int receive;
  //初始化Socket对象,使用Raw套接字发送ICMP协议
  Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
  //或得远程主机IP地址
  IPHostEntry iphtentry = Dns.GetHostEntry(hostTextBox.Text);
  //使用指定的地址和端口号初始化IPEndPoint对象
  IPEndPoint ipendp = new IPEndPoint(iphtentry.AddressList[0],0);
  //使用IPEndPoint对象初始化EndPoint对象
  EndPoint endp = (EndPoint)ipendp;
  //新建一个ICMP对象
  ICMP pkt = new ICMP();
  //设置ICMP包的类型为查询报文,会送请求
  pkt.packType = 0x08;
  //ICMP包的代码之为0
  pkt.packCode = 0x00;
  //校验和为0
  pkt.CheckSum = 0;
  //填写消息标识符
  Buffer.BlockCopy(BitConverter.GetBytes((short)1),0,pkt.Msg,0,2);
  //填写消息序列
  Buffer.BlockCopy(BitConverter.GetBytes((short)1),0,pkt.Msg,2,2);
  //填写包中的数据
  msgData = Encoding.ASCII.GetBytes("This is a text packet");
  Buffer.BlockCopy(msgData,0,pkt.Msg,4,msgData.Length);
  //设置ICMP包的大小
  pkt.msgSize = msgData.Length + 4;
  int pktsize = pkt.msgSize + 4;
  //或得ICMP包中校验和 
  UInt16 checksum = pkt.getChecksum();
  //将包中的校验和填入
  pkt.CheckSum = checksum;
  //设置套接字时间
  host.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,3000);
  //使用套接字发送ICMP包
  host.SendTo(pkt.getBytes(),pktsize,SocketFlags.None,ipendp);
  try
  {
  msgData=new byte[1024];

  //接收返回的数据包
  receive = host.ReceiveFrom(msgData,ref endp);
  }
  catch (SocketException)
  {
  //如果接收失败,则弹出发送失败消息
  msgListBox.Items.Add("远程主机没有消息!");
  return;
  }
  finally
  { 
   
  }
  //使用或得的返回消息构造ICMP
  ICMP res = new ICMP(msgData,receive);
  //显示ICMP包发送端的位置
  msgListBox.Items.Add("受到来自"+endp.ToString()+"消息");
  //显示ICMP包的类型
  msgListBox.Items.Add("类型为"+res.getTypeTrans());
  //显示ICMP包的代码
  msgListBox.Items.Add("代码值为"+res.packCode);
  //或得ICMP包的标识和队列字段
  int Idf = BitConverter.ToInt16(res.Msg,0);
  int Seq = BitConverter.ToInt16(res.Msg,2);
  //显示ICMP包的标识和队列
  msgListBox.Items.Add("表示符为"+Idf);
  msgListBox.Items.Add("序列号为"+Seq);
  //获得ICMP包的数据信息
  string strData = Encoding.ASCII.GetString(res.Msg,4,res.msgSize-4);
  //显示ICMP包的数据信息
  msgListBox.Items.Add("数据包为"