socket编程实现ping

各位仁兄,任姐,在下急需ping测试程序,用socket编程实现ping 功能的方法
作课设用,帮帮忙啦

第1个回答  2006-12-15
C#:

class Ping
{
const int SOCKET_ERROR = -1;
const int ICMP_ECHO = 8;
public static OnPingLog onpinglog=null;
protected static PingLog plog=new PingLog();
public static void WirteLog(string s)
{
Ping.plog.writelog(s);
if(onpinglog!=null)
{
onpinglog(s);
}
}

public static UInt16 checksum(UInt16[] buffer,int size)
{
Int32 cksum = 0;
int counter = 0;
while (size>0)
{
UInt16 val = buffer[counter];
cksum += Convert.ToInt32(buffer[counter]);
counter++;
size--;
}

cksum = (cksum >> 16)+(cksum & 0xffff);
cksum += (cksum >> 16);
return (UInt16)(~cksum);

}

public static Int32 Serialize( IcmpPacket packet,Byte[] Buffer,Int32 PacketSize,Int32 PingData)
{
Int32 cbReturn = 0;
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;

Array.Copy(packet.Data,0,Buffer,Index,PingData);
Index += PingData;

if(Index != PacketSize)
{
cbReturn = -1;
return cbReturn;
}
cbReturn = Index;
return cbReturn;
}

public static void PingHost(string host)
{
IPHostEntry serverHE,fromHE;
int nBytes = 0;
int dwStart = 0;
int dwStop = 0;

Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp);

try
{
//serverHE = Dns.GetHostByName(host);
serverHE = Dns.GetHostByAddress(host.Split(':')[0]);
}
catch(Exception)
{
WirteLog("目标主机" + host + "不存在");
return;
}

//测试端口
// int portNum = 0;
// if(host.Split(':').Length > 1)
// {
// portNum = Int32.Parse(host.Split(':')[1]);
// }
// else
// {
// portNum = 13;
// }
// string hostName = host.Split(':')[0];
// try
// {
// TcpClient client = new TcpClient(hostName, portNum);
// client.Close();
// }
// catch (Exception e)
// {
// WirteLog("错误:" + host + e.Message + "");
// socket.Close();
// return;
// }

IPEndPoint ipepServer;
if(host.Split(':').Length > 1)
{
ipepServer = new IPEndPoint(serverHE.AddressList[0],Int32.Parse(host.Split(':')[1]));
}
else
{
ipepServer = new IPEndPoint(serverHE.AddressList[0],0);
}
EndPoint epServer = (ipepServer);

fromHE = Dns.GetHostByName(Dns.GetHostName());
IPEndPoint ipEndPointFrom;
if(host.Split(':').Length == 1)
{
ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0],0);
}
else
{
ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0],Int32.Parse(host.Split(':')[1]));
}
EndPoint EndPointFrom = (ipEndPointFrom);

int PacketSize = 0;
IcmpPacket packet = new IcmpPacket();

packet.Type = ICMP_ECHO;
packet.SubCode = 0;
packet.CheckSum = UInt16.Parse("0");
packet.Identifier = UInt16.Parse("45");
packet.SequenceNumber = UInt16.Parse("0");

int PingData = 32;
packet.Data = new Byte[PingData];

for(int i=0;i<PingData;i++)
{
packet.Data[i] = (byte)'#';
}

PacketSize = PingData + 8;

Byte[] icmp_pkt_buffer = new Byte[PacketSize];

Int32 Index = 0;

Index = Serialize(packet,icmp_pkt_buffer,PacketSize,PingData);

if(Index == -1)
{
WirteLog("错误(Error in Making Packet)");
return;
}

Double double_length = Convert.ToDouble(Index);
Double dtemp = Math.Ceiling(double_length/2);
int cksum_buffer_length = Convert.ToInt32(dtemp);

UInt16[] cksum_buffer = new UInt16[cksum_buffer_length];

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

UInt16 u_cksum = checksum(cksum_buffer,cksum_buffer_length);

packet.CheckSum = u_cksum;

Byte[] sendbuf = new Byte[PacketSize];
Index = Serialize(packet,sendbuf,PacketSize,PingData);

if(Index == -1)
{
WirteLog("错误(Error in Making Packet)");
return;
}

dwStart = System.Environment.TickCount;

if((nBytes = socket.SendTo(sendbuf,PacketSize,0,epServer)) == SOCKET_ERROR)
{
WirteLog("错误(Socket Error can not Sending Packet)");
}

Byte[] ReceiveBuffer = new Byte[256];
nBytes = 0;

bool recd = false;
int timeout = 0;

while(!recd)
{
nBytes = socket.ReceiveFrom(ReceiveBuffer,256,0,ref EndPointFrom);
if(nBytes == SOCKET_ERROR)
{
WirteLog("错误(远程主机没有响应)");
recd = true;
break;
}
else if(nBytes > 0)
{
dwStop = System.Environment.TickCount - dwStart;
WirteLog("成功(Reply from"+epServer.ToString()+":bytes = "+ nBytes.ToString()+"time = "+dwStop +"ms)");
recd = true;
break;
}

timeout = System.Environment.TickCount - dwStart;
if(timeout > 1000)
{
WirteLog("错误(超时)");
recd = true;
}
}
socket.Close();

}

}

public class IcmpPacket
{
public IcmpPacket()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

public Byte Type;
public Byte SubCode;
public UInt16 CheckSum;
public UInt16 Identifier;
public UInt16 SequenceNumber;
public Byte[] Data;
}

socket编程实现ping
const int SOCKET_ERROR = -1;const int ICMP_ECHO = 8;public static OnPingLog onpinglog=null;protected static PingLog plog=new PingLog();public static void WirteLog(string s){ Ping.plog.writelog(s);if(onpinglog!=null){ onpinglog(s);} } publ...

怎样用SOCKET实现PING的功能,是发一个ICMP包吗
对,socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);起始搜索下就很多,比如:http:\/\/blog.csdn.net\/cbuttonst\/article\/details\/7610801

我在做一个C\/S socket编程,在一台电脑上客户端和服务器之间可以正常发送...
两台电脑必须都是铁通的,必须都没有在内网(没有使用路由器)。才能连通

...用Socket设计一个软件,能实现ping功能,要有界面的。
思路1. 使用linux系统命令ping。 你的程序中fork一个新进程,在新进程里面通过system("ping xxxx");的方式来调用系统ping命令,然后把ping命令的输出通过管道输入到你的程序中来。思路2. 从网上找一个c语言写的现成的ping源代码,有很多的。看懂了以后,把ping源代码集成到你的代码中(把ping的main...

ping命令全链路分析(3)-用户态数据包构造与传递
当目的端返回ping命令的响应报文被网卡接收后,通过内核网络协议栈处理后返回给应用程序。ping应用程序采用IO复用中的select()方式来处理响应报文,当监控到对应socket连接中有数据包到来时,调用ping_recv()函数处理ICMP响应数据包。应用层软件ping通过socket接口与内核通信,实现数据包发送和接收。数据包发送...

windows下socket如何编程
Ping命令是用来进行网络连接测试的一个程序,其对应的文件名为“ping.exe”。根据不同的测试目的,此命令可以带上不同的参数。

如何用C语言编程实现 dos中的ping程序?
步骤是 1. 建立一个socket int sock=socket(AF_INTE,SOCK_RAW,"你的目标主机地址");2. connect(sock,sock_address...)3. send(sock...)具体的函数参数可以搜索一下,大概步骤就是这样 例子程序可以参考:http:\/\/hi.baidu.com\/relax0626\/blog\/item\/ef9b723d57f498ee3d6d97a2.html http:\/\/...

linux下如何用socket套接字来代替ping程序来检测终端网络连通性??急求...
myping.c include <stdio.h> include <stdlib.h> include <string.h> include <errno.h> include <sys\/socket.h> include <sys\/types.h> include <netinet\/in.h> include <arpa\/inet.h> include <netdb.h> include <sys\/time.h> include <netinet\/ip_icmp.h> include <unistd.h> inc...

ping命令如何使用?
步骤:win键+R,并输入cmd 输入ping www.baidu.com,ping通后就会出现已连接的数据包信息。命令参数:-d 使用Socket的SO_DEBUG功能。-f 极限检测。大量且快速地送网络封包给一台机器,看它的回应。-n 只输出数值。-q 不显示任何传送封包的信息,只显示最后的结果。-r 忽略普通的Routing Table,...

我想要ping一百个域名,想用多线程,启是个线程,每个线程ping10个域名...
socket def ReadHost(file):hosts=[]...return hosts class ThreadClass(threading.Thread): def __init__(self,host): self.host=host threading.Thread.__init__(self) def run(self): global IPhost try: res=socket.getaddrinfo(self.host,None) if mutex.acquire...

相似回答