• 网络学院
  • IT资讯
  • 操作系统
  • 网络技术
  • 软件应用
  • 办公软件
  • 编程技术
  • 网站架设
  • 数据库类
  • 平面设计
  • 多媒体类
  • 游戏资讯
  • 教学论文
  • 认证考试
在C#中实现Ping
  站点:
  • 首 页
  • 最新软件
  • 文章教程
  • 国内软件
  • 国外软件
  • 绿色软件
  • 源码下载
  • 字体下载
在C#中实现Ping
软件发布 在C#中实现Ping
网络软件 系统工具 应用软件 联络聊天 图形图像 多媒体类 行业软件 游戏娱乐 编程开发 安全相关 教育教学 数码软件 绿软下载
热门软件: QQ 瑞星 pplive e话通 木马克星 千千静听 office2000 五笔字根 Photoshop 视频分割
返回文章教程首页 >> 文章首页 >> 编程技术 >> C#教程 >> 在C#中实现Ping

在C#中实现Ping

添加时间: 2007-7-11 3:51:43  作者: C#教程  阅读次数:120   来源: http://www.d9soft.com

       

    在C#中实现Ping,代码如下:

using System;
using System.Drawing;
using System.Collections;
using System.Data;
using System<a href="http://dev.21tx.com/dotnet/" target="_blank">.net</a>;
using System.Net.Sockets;

///  Ping类
public class Ping
{
//声明常量
const int SOCKET_ERROR = -1;
const int ICMP_ECHO = 8;

// 程序入口
public static void Main()
{
 Ping p = new Ping();
 Console.WriteLine("请输入要 Ping 的IP或者主机名字:");
 string MyUrl = Console.ReadLine();
 Console.WriteLine("正在 Ping " + MyUrl + " ……");
 Console.Write(p.PingHost(MyUrl));
}

public string PingHost(string host)
{
 // 声明 IPHostEntry
 IPHostEntry serverHE, fromHE;
 int nBytes = 0;
 int dwStart = 0, dwStop = 0;

 //初始化ICMP的Socket
 Socket socket =
  new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
       socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000);
 // 得到Server EndPoint
 try
 {
  serverHE = Dns.GetHostByName(host);
 }
 catch(Exception)
 {

  return "没有发现主机";
 }

 // 把 Server IP_EndPoint转换成EndPoint
 IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0], 0);
 EndPoint epServer = (ipepServer);

 // 设定客户机的接收Endpoint
 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; //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];

 // 初始化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 )
 {
   return "Error Creating Packet";
 }

 // convert into a UInt16 array

 //Get the Half size of the Packet
 Double double_length = Convert.ToDouble(Index);
 Double dtemp = 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 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 )
 {
   return "Error Creating Packet";

 }


 dwStart = System.Environment.TickCount; // Start timing
 //send the Packet over the socket
 if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR)
 {
   return "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 ;

 //loop for checking the time of the server responding
 while(!recd)
 {
  nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom);
  if (nBytes == SOCKET_ERROR)
  {
   return "主机没有响应" ;

  }
  else if(nBytes>0)
  {
   dwStop = System.Environment.TickCount - dwStart; // stop timing
    return "Reply from "+epServer.ToString()+" in "
    +dwStop+"ms.  Received: "+nBytes+ " Bytes.";


  }
  timeout=System.Environment.TickCount - dwStart;
  if(timeout>1000)
  {
   return "超时" ;
  }
 }

 //close the socket
 socket.Close();
 return "";
}
/// <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);

 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;

 // 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);
}
}
/// 类结束
/// <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;

} // class IcmpPacket

 

上下文章:

 

上一篇文章: 浅析C#中图形编程 下一篇文章: 通过查询结果进行分页

相关文章:

  • 飞速在线看视频 傲盾加速帮你实现速度感受
  • 用端口碰撞技术实现服务器远程管理
  • servlet实现oracle中读出文件并显示
  • 在Oracle中实现数据库的复制
  • 在T-SQL中实现Oracle的MINUS集合运算符

相关软件:

  • Ping Pong 3D 1.4
  • KP Typing Tutor 6.8
  • KP Typing Tutor 4.02 汉化补丁
  • AutoTyping 1.1 英文版
  • Tiray Blog Ping工具 V1.1
  • Ping Tester V2008.2.18

 

快速导航

  • 网络学院
  • 精品汇聚
  • 字体下载
  • 教程下载
  • ASP源码
  • PHP源码
  • Net源码
  • JSP 源码

编程技术分类导航

  • ASP & ASP.NET教程
  • PHP教程
  • JSP教程
  • C/C++教程
  • VB & VB.NET教程
  • VC教程
  • Delphi教程
  • BCB教程
  • VFP教程
  • PB教程
  • JAVA教程
  • XML教程
  • C#教程
  • CGI教程

本类经典文章推荐

  • ADO.NET的开发场景及传统ADO的处理
  • 利用Visual C#实现Window管道技术
  • C#取得汉字的拼音的首字母
  • 使用C#编写DES加密程序的framework
  • Visual C#编写3D游戏框架示例
  • 用C#和本地Windows API操纵系统菜...
  • 在C#程序设计中使用Win32类库
  • Visual C#中调用Windows服务初探
  • 如何在C#的WinForm中制作饼状图和...
  • C#中实现DataGrid双向排序

C#教程阅读排行

  • 如何在C#的WinForm中制作饼状图和...
  • 浅析C#中图形编程
  • 用C#和本地Windows API操纵系统菜...
  • 彻底剖析C# 2.0泛型类的创建和使用
  • 使用C#编写DES加密程序的framework
  • Visual C#编写3D游戏框架示例
  • Visual C#中调用Windows服务初探
  • C#如何在Form中嵌入并且操作Excel...
  • Visual C# 2005实现控件中捕获按键
  • C#中利用mediaplayer打造mp3播放器

编程技术阅读总排行

  • VB入门教程之一
  • Java连接数据库实例
  • 第二章 PowerBuilder 入门之创建新...
  • VC++之List Box/Check List Box控...
  • 第一章 什么是PowerBuilder
  • VC++ List Ctrl控件
  • VC++ Combo Box/Combo Box Ex控件
  • 学C++不得不看的一篇文章
  • VB入门教程之二
  • VC++之Button控件

广告位置

字母检索 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 回到顶部

关于我们 | 版权声明 | 免责条款 | 广告联系 | 软件发布 | 下载帮助 | 下载排行 | 网站地图 | 特别鸣谢 | 友情连接

copyright; 2005-2008 D9soft.com 第九软件网 版权所有