C# 抓包工具
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CatchTool
{
class Program
{
private static Socket socket = null;
static void Main(string[] args)
{
string localIP = "192.168.10.6";
socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Bind(new IPEndPoint(IPAddress.Parse(localIP), 0));
socket.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[4]);
Thread t = new Thread(Execute);
t.IsBackground = true;
t.Start();
Console.WriteLine("start...");
Console.ReadLine();
}
private static void Execute()
{
while (true)
{
try
{
byte[] buffer = new byte[10240];
int count = socket.Receive(buffer);
if (count > 0)
{
int headerLen = (buffer[0] & 0xf) * 4;
if (buffer[9] == (int)ProtocolType.Tcp)
{
byte[] data = new byte[count - headerLen];
Array.Copy(buffer, headerLen, data, 0, data.Length);
byte[] sourceIpData = new byte[4];
Array.Copy(buffer, 12, sourceIpData, 0, 4);
byte[] destIpData = new byte[4];
Array.Copy(buffer, 16, destIpData, 0, 4);
string sourceIp = $"{sourceIpData[0]}.{sourceIpData[1]}.{sourceIpData[2]}.{sourceIpData[3]}";
string destIp = $"{destIpData[0]}.{destIpData[1]}.{destIpData[2]}.{destIpData[3]}";
Console.WriteLine($"source IP={sourceIp} ,destination IP={destIp}");
}
}
}
catch (Exception)
{
throw;
}
}
}
}
}