110,571
社区成员
发帖
与我相关
我的任务
分享
//解析接收的数据包,形成PacketArrivedEventArgs事件数据类对象,并引发PacketArrival事件
unsafe private void Receive(byte[] buf, int len)
{
byte temp_protocol = 0;
uint temp_version = 0;
uint temp_ip_srcaddr = 0;
uint temp_ip_destaddr = 0;
short temp_srcport = 0;
short temp_dstport = 0;
IPAddress temp_ip;
PacketArrivedEventArgs e = new PacketArrivedEventArgs();//新网络数据包信息事件
fixed (byte* fixed_buf = buf)
{
IPHeader* head = (IPHeader*)fixed_buf;//把数据流整和为IPHeader结构
e.HeaderLength = (uint)(head->ip_verlen & 0x0F) << 2;
temp_protocol = head->ip_protocol;
switch (temp_protocol)//提取协议类型
{
case 1: e.Protocol = "ICMP"; break;
case 2: e.Protocol = "IGMP"; break;
case 6: e.Protocol = "TCP"; break;
case 17: e.Protocol = "UDP"; break;
default: e.Protocol = "UNKNOWN"; break;
}
temp_version = (uint)(head->ip_verlen & 0xF0) >> 4;//提取IP协议版本
e.IPVersion = temp_version.ToString();
//以下语句提取出了PacketArrivedEventArgs对象中的其他参数
temp_ip_srcaddr = head->ip_srcaddr;
temp_ip_destaddr = head->ip_destaddr;
temp_ip = new IPAddress(temp_ip_srcaddr);
e.OriginationAddress = temp_ip.ToString();
temp_ip = new IPAddress(temp_ip_destaddr);
e.DestinationAddress = temp_ip.ToString();
temp_srcport = *(short*)&fixed_buf[e.HeaderLength];
temp_dstport = *(short*)&fixed_buf[e.HeaderLength + 2];
e.OriginationPort = IPAddress.NetworkToHostOrder(temp_srcport).ToString();
e.DestinationPort = IPAddress.NetworkToHostOrder(temp_dstport).ToString();
e.PacketLength = (uint)len;
e.MessageLength = (uint)len - e.HeaderLength;
e.ReceiveBuffer = buf;
//把buf中的IP头赋给PacketArrivedEventArgs中的IPHeaderBuffer
Array.Copy(buf, 0, e.IPHeaderBuffer, 0, (int)e.HeaderLength);
//把buf中的包中内容赋给PacketArrivedEventArgs中的MessageBuffer
Array.Copy(buf, (int)e.HeaderLength, e.MessageBuffer, 0, (int)e.MessageLength);
}
//引发PacketArrival事件
PacketArrival(this, e);
}
public static readonly object objLock = new object();
public static void put(PacketArrivedEventArgs args)
{
string filename = AppDomain.CurrentDomain.BaseDirectory + "log/" + DateTime.Now.ToString("yyyy-MM-ddHH") + ".txt";
lock (objLock)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true))
{
sw.WriteLine(args.Protocol + " " + args.IPVersion + ": " + args.OriginationAddress + ":" + args.OriginationPort + "==>>" + args.DestinationAddress + ":" + args.DestinationPort + " 包长度:" + args.PacketLength + " 头长度:" + args.HeaderLength + " 数据长度:" + args.MessageLength);
sw.WriteLine("数据:" + System.Text.Encoding.Default.GetString(args.ReceiveBuffer));
sw.WriteLine("===========================================================================");
}
}
}