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. Winform、WPF、Silverlight、MFC区别与联系

    WinForm 在Windows中,诸如窗体绘制等功能由GDI(图形设备接口)实现,放在操作系统内核中.Windows Forms在底层使用的是GDI+.GDI+是GDI的“面向对象包装”,使用C++ ...

  2. Des加解密(Java端和Js端配套)解析

    一.什么是DES加密        des对称加密,对称加密,是一种比较传统的加密方式,其加密运算.解密运算使用的是同样的密钥,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码( ...

  3. INSTALL_FAILED_SHARED_USER_INCOMPATIBLE的问题

    eclipse编译出来的apk,安装时报出INSTALL_FAILED_SHARED_USER_INCOMPATIBLE的错误. 原因:apk的AndroidManifest.xml中声明了andro ...

  4. JBPM的ORACLE脚本

    create table JBPM4_DEPLOYMENT ( DBID_ number(19,0) not null, NAME_ clob, TIMESTAMP_ number(19,0), ST ...

  5. spring mvc静态资源访问的配置

    如果我们使用spring mvc来做web访问请求的控制转发,那么默认所有访问都将被DispatcherServlet独裁统治.比如我现在想访问的欢迎页index.html根本无需任何业务逻辑处理,仅 ...

  6. MySQL-5.7中InnoDB表数据文件存储位置

    学习地址:https://www.cnblogs.com/tongxiaoda/p/7874535.html

  7. php单链表实现

    php单链表实现 <?php //单链表 class Hero{ public $no; public $name; public $nickname; public $next=null; f ...

  8. iSCSI存储的3种连接方式

    我们分析了iSCSI存储的系统结构,下面来看iSCSI是如何与服务器.工作站等主机设备来连接的,也就是我们如何建立一个iSCSI网络存储系统. iSCSI设备的主机接口一般默认都是IP接口,可以直接与 ...

  9. MFC学习(六)计算器

    1 stdafx.h  所谓头文件预编译,就是把一个工程(Project)中使用的一些MFC标准头文件(如Windows.H.Afxwin.H)预先编译,以后该工程编译时,不再编译这部分头文件,仅仅使 ...

  10. ASP.NET页面传值加号变空格解决办法

    只需要把欲传值进行编码 string EncodeId = Server.UrlEncode(id); 加号就变成了 % 2 B  (中间无空格) 然后再传出去. Request.QueryStrin ...