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

 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)
{
Ping ping = new Ping();
Console.WriteLine(ping.Send("192.168.0.33").Status);
Console.Read();
}
} }

2>同过调用cmd 的ping实现

 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)
{
Console.WriteLine(PingByProcess("192.168.0.33"));
Console.Read();
} static string PingByProcess(string ip)
{
using (Process p = new Process())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true; p.Start();
p.StandardInput.WriteLine(string.Format("ping -n 1 {0}", ip));
return p.StandardOutput.ReadToEnd();
}
}
} }

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

 using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets; public class PingHelp
{
const int SOCKET_ERROR = -;
const int ICMP_ECHO = ; public string PingHost(string host)
{
// 声明 IPHostEntry
IPHostEntry ServerHE, fromHE;
int nBytes = ;
int dwStart = , dwStop = ; //初始化ICMP的Socket
Socket socket =
new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, );
// 得到Server EndPoint
try
{
ServerHE = Dns.GetHostByName(host);
}
catch (Exception)
{ return "没有发现主机";
} // 把 Server IP_EndPoint转换成EndPoint
IPEndPoint ipepServer = new IPEndPoint(ServerHE.AddressList[], );
EndPoint epServer = (ipepServer); // 设定客户机的接收Endpoint
fromHE = Dns.GetHostByName(Dns.GetHostName());
IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[], );
EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = ;
IcmpPacket packet = new IcmpPacket(); // 构建要发送的包
packet.Type = ICMP_ECHO; //8
packet.SubCode = ;
packet.CheckSum = ;
packet.Identifier = ;
packet.SequenceNumber = ;
int PingData = ; // sizeof(IcmpPacket) - 8;
packet.Data = new Byte[PingData]; // 初始化Packet.Data
for (int i = ; i < PingData; i++)
{
packet.Data[i] = (byte)'#';
} //Variable to hold the total Packet size
PacketSize = ;
Byte[] icmp_pkt_buffer = new Byte[PacketSize];
Int32 Index = ;
//again check the packet size
Index = Serialize(
packet,
icmp_pkt_buffer,
PacketSize,
PingData);
//if there is a error report it
if (Index == -)
{
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 / );
int cksum_buffer_length = Index / ;
//Create a Byte Array
UInt16[] cksum_buffer = new UInt16[cksum_buffer_length];
//Code to initialize the Uint16 array
int icmp_header_buffer_index = ;
for (int i = ; i < cksum_buffer_length; i++)
{
cksum_buffer[i] =
BitConverter.ToUInt16(icmp_pkt_buffer, icmp_header_buffer_index);
icmp_header_buffer_index += ;
}
//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 == -)
{
return "Error Creating Packet"; } dwStart = System.Environment.TickCount; // Start timing
//send the Packet over the socket
if ((nBytes = socket.SendTo(sendbuf, PacketSize, , 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[];
nBytes = ;
//Receive the bytes
bool recd = false;
int timeout = ; //loop for checking the time of the server responding
while (!recd)
{
nBytes = socket.ReceiveFrom(ReceiveBuffer, , , ref EndPointFrom);
if (nBytes == SOCKET_ERROR)
{
return "主机没有响应"; }
else if (nBytes > )
{
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 > )
{
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 = ;
// serialize the struct into the array
int Index = ; Byte[] b_type = new Byte[];
b_type[] = (packet.Type); Byte[] b_code = new Byte[];
b_code[] = (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, , Buffer, Index, b_type.Length);
Index += b_type.Length; Array.Copy(b_code, , Buffer, Index, b_code.Length);
Index += b_code.Length; Array.Copy(b_cksum, , Buffer, Index, b_cksum.Length);
Index += b_cksum.Length; Array.Copy(b_id, , Buffer, Index, b_id.Length);
Index += b_id.Length; Array.Copy(b_seq, , Buffer, Index, b_seq.Length);
Index += b_seq.Length; // copy the data
Array.Copy(packet.Data, , Buffer, Index, PingData);
Index += PingData;
if (Index != PacketSize/* sizeof(IcmpPacket) */)
{
cbReturn = -;
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 = ;
int counter;
counter = ; while (size > )
{
UInt16 val = buffer[counter]; cksum += buffer[counter];
counter += ;
size -= ;
} cksum = (cksum >> ) + (cksum & 0xffff);
cksum += (cksum >> );
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
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();
}
} }

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

c# 下实现ping 命令操作的更多相关文章

  1. 解决:Ubuntu12.04下使用ping命令返回ping:icmp open socket: Operation not permitted的解决

    ping命令在运行中采用了ICMP协议,需要发送ICMP报文.但是只有root用户才能建立ICMP报文.而正常情况下,ping命令的权限应为-rwsr-xr-x,即带有suid的文件,一旦该权限被修改 ...

  2. windows下cmd中命令操作

    windows下cmd中命令:   cls清空 上下箭头进行命令历史命令切换 ------------------------------------------------------------- ...

  3. linux下安装 ping 命令

    使用docker仓库下载的ubuntu 14.04 镜像.里面精简的连 ping 命令都没有.google 百度都搜索不到ping 命令在哪个包里. 努力找了半天,在一篇文章的字里行间发现了 ping ...

  4. Linux场景下的辅助命令操作汇总

    ============================================ 1.客户端: SecureCRT 7.1 或者putty 2.FTP 主要是上传文件往Linux,否则我们就的 ...

  5. ubuntu下没有ping命令

    root@node2:/# apt-get install inetutils-ping

  6. Linux和Windows下ping命令详解(转:http://linux.chinaitlab.com/command/829332.html)

    一.Linux下的ping参数 用途 发送一个回送信号请求给网络主机. 语法 ping [ -d] [ -D ] [ -n ] [ -q ] [ -r] [ -v] [ \ -R ] [ -a add ...

  7. docker下centos安装ping命令

    https://blog.csdn.net/king_gun/article/details/78423115 [问题] 从docker hub上拉取到则镜像centos:6.7在执行ping命令是报 ...

  8. Linux和Windows下ping命令详解

    转:http://linux.chinaitlab.com/command/829332.html 一.Linux下的ping参数 用途 发送一个回送信号请求给网络主机. 语法 ping [ -d] ...

  9. ping命令的几个简单使用

    发觉linux下的ping命令花样还挺多的,下面是几个例子 1.ping www.baidu.com,最粗糙的用法,此时主机将不停地向目的地址发送ICMP echo request数据包,直至你按下C ...

随机推荐

  1. 【学习】JennyHui学自动化测试

    学习材料:虫师的Python书,乙醇的教程 Selenium 常用的键盘事件 智能等待 处理富文本框 定位 界面数据与数据库数据对比 Excel操作 下载文件 Selenium 2.0 学习笔记 == ...

  2. Proposition

    提供 \(k\) 个变量 \((k\leq 4)\) 可独立取值为 \(0,1\),两种运算分别等价于 \(\neg a\) 和 \(\neg a \lor b\) . 你需要恰好使用 \(n\) 个 ...

  3. HohoCoder 1184 : 连通性二·边的双连通分量(+原理证明)

    1184 : 连通性二·边的双连通分量 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 在基本的网络搭建完成后,学校为了方便管理还需要对所有的服务器进行编组,网络所的老师 ...

  4. PS基础教程:[8]蒙版使用实例

    蒙版是PS中我们最常使用的工具,使用蒙版合成图片可以制作出非常绚丽的效果,并且看上去感觉很真,下面就以一个实例为大家分享一下蒙版的基本使用. 方法 1.在PS中打开准备好的素材,这里主要介绍蒙版的使用 ...

  5. 【JQuery】学习

    JavaScript参考 JQuery 学习总结及实例 1.JQuery概念 A.Jquery是一个优秀的Javascript框架.它是轻量级的js库 ,它兼容CSS3,还兼容各种浏览器,jQuery ...

  6. css处理最后一个li

    .relatebar li{width:98px;height:146px;padding:5px;float:left;border-left:1px solid #ccc;} .relatebar ...

  7. 【openCV学习笔记】在Mac上配置openCV步骤详解

    (1)安装Homebrew:(需要Ruby) 注:因为snow leopard 以后已经自带Ruby了,所有可以不用自己安装Ruby. 看一下Homebrew的官网: http://mxcl.gith ...

  8. 对于global的介绍

    抄自http://veniceweb.googlecode.com/svn/trunk/public/daily_tech_doc/erlang_global_20091109.txt 1. 介绍:这 ...

  9. 几种经典的hash算法

    计算理论中,没有Hash函数的说法,只有单向函数的说法.所谓的单向函数,是一个复杂的定义,大家可以去看计算理论或者密码学方面的数据.用“人 类”的语言描述单向函数就是:如果某个函数在给定输入的时候,很 ...

  10. mina中责任链模式的实现

    一.mina的框架回顾 责任链模式在mina中有重要的作用,其中Filter机制就是基于责任链实现的. 从上图看到消息的接受从IoService层先经过Filter层过滤处理后最后交给IoHander ...