Skip to content

Instantly share code, notes, and snippets.

@abcsharp
Created June 9, 2013 16:59
Show Gist options
  • Save abcsharp/5744289 to your computer and use it in GitHub Desktop.
Save abcsharp/5744289 to your computer and use it in GitHub Desktop.
C#でping(要管理者権限)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace PingSample
{
class Program
{
static void Main(string[] args)
{
if(args.Length<1) Console.WriteLine("Usage: PingSample {IP}");
else{
IPAddress ip;
if(!IPAddress.TryParse(args[0],out ip)){
Console.WriteLine("Invalid IP...");
return;
}
SendPing(ip);
}
}
static void SendPing(IPAddress ip)
{
var icmpHeader=new List<byte>(){
0x08,0x00,0x00,0x00,
/* id */0x00,0x00};
icmpHeader.InsertRange(4,BitConverter.GetBytes((ushort)Process.GetCurrentProcess().Id).Reverse());
icmpHeader.AddRange(Encoding.ASCII.GetBytes("hi,whats up?"));
var icmpHeaderChecksum=BitConverter.GetBytes(ComputeChecksum(icmpHeader.ToArray()));
icmpHeader[2]=icmpHeaderChecksum[0];
icmpHeader[3]=icmpHeaderChecksum[1];
var socket=new Socket(AddressFamily.InterNetwork,SocketType.Raw,ProtocolType.Icmp);
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.SendTimeout,1000);
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,1000);
try{
Console.WriteLine("Send ping to "+ip.ToString()+"...");
socket.SendTo(icmpHeader.ToArray(),new IPEndPoint(ip,0));
var buffer=new byte[128];
socket.Receive(buffer);
}catch(Exception){
Console.WriteLine("Failed!");
}
Console.WriteLine("Success!");
}
static ushort ComputeChecksum(byte[] data)
{
var shortPacket=from i in Enumerable.Range(0,data.Length).Where(i=>i%2==0)
select BitConverter.ToUInt16(data,i);
var sum=shortPacket.Sum(s=>(int)s);
while(sum>>16!=0) sum=(sum&0xFFFF)+(sum>>16);
return (ushort)~sum;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment