C#实现抓包,并过滤UDP
using PacketDotNet;
using SharpPcap;
using SharpPcap.LibPcap;
using System;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace ConsoleAppSharppcap
{
internal class Program
{
static void Main(string[] args)
{
LibPcapLiveDeviceList devices = LibPcapLiveDeviceList.Instance;
string ToHex(byte[] data)
{
return BitConverter.ToString(data).Replace("-", string.Empty);
}
string GetRoomNumber(byte[] data)
{
return data[26].ToString() + data[27].ToString("D2");
}
bool IsSOS(byte[] data)
{
return (data[72] == 1);
}
void auto_msg_5e00(byte[] data)
{
if (ToHex(data.Take(2).ToArray()) != "5E00")
{
return;
}
//bool bIsSOS = IsSOS(data);
if (true)
{
Console.WriteLine("{0},{1}", GetRoomNumber(data), data[72]);
}
Response.DataContractData rdata = new Response.DataContractData();
rdata.Id = GetRoomNumber(data);
rdata.IsSOS = data[72];
byte[] data2 = Encoding.UTF8.GetBytes(JSON.Stringify(rdata));
UdpClient udpClient = new UdpClient();
udpClient.Send(data2, data2.Length, "172.19.19.0", 12388);
}
void Device_OnPacketArrival(object s, PacketCapture e)
{
RawCapture ePacket = e.GetPacket();
Packet packet = Packet.ParsePacket(ePacket.LinkLayerType, ePacket.Data);
if (packet is EthernetPacket ethernetPacket)
{
if (ethernetPacket.PayloadPacket is IPPacket ipPacket)
{
//Console.WriteLine($"From {ipPacket.SourceAddress} To {ipPacket.DestinationAddress}");
if (ipPacket.PayloadPacket is UdpPacket udpPacket)
{
if (udpPacket.DestinationPort == 2388)
{
auto_msg_5e00(udpPacket.PayloadData);
return;
Console.WriteLine($"From {ipPacket.SourceAddress}:{udpPacket.SourcePort} To {ipPacket.DestinationAddress}:{udpPacket.DestinationPort}");
Console.WriteLine($"Packet Length: {udpPacket.PayloadData.Length} bytes");
Console.WriteLine();
}
}
}
}
}
foreach (LibPcapLiveDevice device in devices)
{
device.Open();
device.OnPacketArrival += Device_OnPacketArrival;
device.StartCapture();
}
Console.ReadLine();
}
}
}
标签:UDP,Console,C#,udpPacket,return,ipPacket,using,data,抓包 From: https://blog.51cto.com/xiangxisheng/8438620