日期:2009-07-27  浏览次数:20453 次

导 读:PING 是一个用来检测网络连接速度的使用工具,下面的文章将介绍在C#中利用System.Net.Sockets 来创建一个自己的PING 工具。

--------------------------------------------------------------------------------

PING 是一个用来检测网络连接速度的工具,它会在本机和给出的远程主机名之间建立一个SOCKET 连接并向其发送一个ICMP协议格式的数据包,然后远程主机作出响应,发回一个数据包,通过计算发送到接收数据包的时间间隔,我们可以确定连接的速度。

使用方法 ping <hostname> [/r]

<hostname> 主机名

[/r] 可选属性,决定是否连续的 ping 远程主机。

下面是代码:

///ping.cs

namespace SaurabhPing

{

using System;

using System.Net;

using System.Net.Sockets;

/// <summary>

/// 主要的类:ping

/// </summary>

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);

// 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];