-- 作者:卷积内核
-- 发布时间:7/24/2012 10:07:00 AM
-- C# Socket 异步接受网络广播
必须设置SOCKET为低级操作模式 byte[] InByte = new byte[4] { 1, 0, 0, 0 }; byte[] OutByte = new byte[4]; int SIO_RCVALL = unchecked((int)0x98000001); int ScoketCode = MySocket.IOControl(SIO_RCVALL, InByte, OutByte); ScoketCode = OutByte[0] + OutByte[1] + OutByte[2] + OutByte[3]; 数据包的结构 [StructLayout(LayoutKind.Explicit)] public struct IPHeader { [FieldOffset(0)] public byte ip_verlen; //IP version and IP Header length Combined [FieldOffset(1)] public byte ip_tos; //Type of Service [FieldOffset(2)] public ushort ip_totallength; //Total Packet Length [FieldOffset(4)] public ushort ip_id; //Unique ID [FieldOffset(6)] public ushort ip_offset; //Flags and Offset [FieldOffset(8)] public byte ip_ttl; //Time To Live [FieldOffset(9)] public byte ip_protocol; //Protocol (TCP, UDP, ICMP, Etc.) [FieldOffset(10)] public ushort ip_checksum; //IP Header Checksum [FieldOffset(12)] public uint ip_srcaddr; //Source IP Address [FieldOffset(16)] public uint ip_destaddr; //Destination IP Address } 下面是全部代码 using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; namespace ReceiveAll { public class MyRawSocket { private IPAddress MyIP; private bool RunRawSocket = false; private Socket MySocket; public MyRawSocket(IPAddress MyIPAddress) { MyIP = MyIPAddress; MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); MySocket.Blocking = false; MySocket.Bind(new IPEndPoint(MyIPAddress, 0)); if (SetSocketIOControl() == false) return; RunRawSocket = true; } private bool SetSocketIOControl() { bool ReturnBool = true; try { MySocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); byte[] InByte = new byte[4] { 1, 0, 0, 0 }; byte[] OutByte = new byte[4]; int SIO_RCVALL = unchecked((int)0x98000001); int ScoketCode = MySocket.IOControl(SIO_RCVALL, InByte, OutByte); ScoketCode = OutByte[0] + OutByte[1] + OutByte[2] + OutByte[3]; if (ScoketCode != 0) ReturnBool = false; } catch (SocketException) { ReturnBool = false; } return ReturnBool; } public void Star() { byte[] Temp = new byte[0]; IAsyncResult StarAsyncResult = MySocket.BeginReceive(Temp, 0, 0, SocketFlags.None, new AsyncCallback(CallReceive), MySocket); } public void Stop() { RunRawSocket = false; } private void CallReceive(IAsyncResult ar) { Socket sock = (Socket)ar.AsyncState; int ReceiveCount = sock.Available; if (ReceiveCount != 0) { byte[] Data = new byte[ReceiveCount]; sock.Receive(Data); AssayByte(Data); } if (RunRawSocket) Star(); } /// <summary> /// 分析数据 /// </summary> /// <param name="Data"></param> private void AssayByte(byte[] Data) { IPData MyData = new IPData(); if (Data.Length >= 24) { MyData.HeaderLength = (uint)(Data[0] & 0x0F) << 2; MyData.Version = (uint)(Data[0] & 0xF0) >> 4; switch (Data[9]) { case 1: MyData.Protocol = "ICMP"; break; case 2: MyData.Protocol = "IGMP"; break; case 6: MyData.Protocol = "TCP"; break; case 17: MyData.Protocol = "UDP"; break; default: MyData.Protocol = "UNKNOWN"; break; } MyData.OriginationAddress = new IPAddress(new byte[] { Data[12], Data[13], Data[14], Data[15] }); MyData.DestinationAddress = new IPAddress(new byte[] { Data[16], Data[17], Data[18], Data[19] }); MyData.OriginationPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(new byte[] { Data[20], Data[21] }, 0)); MyData.DestinationPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(new byte[] { Data[22], Data[23] }, 0)); MyData.PacketLength = (uint)Data.Length; MyData.MessageLength = (uint)Data.Length - MyData.HeaderLength; MyData.PackByte = Data; } else { MyData.PackByte = Data; } if (Receive != null) Receive(MyData); } public delegate void ReceiveData(IPData ReceiveClass); public event ReceiveData Receive; public class IPData { private uint _HeaderLength = 0; private uint _Version = 0; private string _Protocol = ""; private IPAddress _OriginationAddress; private IPAddress _DestinationAddress; private short _OriginationPort = 0; private short _DestinationPort = 0; private uint _PacketLength = 0; private uint _MessageLength = 0; private byte[] _PackByte; /// <summary> /// IP头长度 /// </summary> public uint HeaderLength { get { return _HeaderLength; } set { _HeaderLength = value; } } /// <summary> /// IP版本 /// </summary> public uint Version { get { return _Version; } set { _Version = value; } } /// <summary> /// IP协议 /// </summary> public string Protocol { get { return _Protocol; } set { _Protocol = value; } } /// <summary> /// 发送IP地址 /// </summary> public IPAddress OriginationAddress { get { return _OriginationAddress; } set { _OriginationAddress = value; } } /// <summary> /// 接收IP地址 /// </summary> public IPAddress DestinationAddress { get { return _DestinationAddress; } set { _DestinationAddress = value; } } /// <summary> /// 发送端口 /// </summary> public short OriginationPort { get { return _OriginationPort; } set { _OriginationPort = value; } } /// <summary> /// 接收端口 /// </summary> public short DestinationPort { get { return _DestinationPort; } set { _DestinationPort = value; } } /// <summary> /// 接收长度 /// </summary> public uint PacketLength { get { return _PacketLength; } set { _PacketLength = value; } } /// <summary> /// 消息长度 /// </summary> public uint MessageLength { get { return _MessageLength; } set { _MessageLength = value; } } /// <summary> /// 包数据 /// </summary> public byte[] PackByte { get { return _PackByte; } set { _PackByte = value; } } } } } 使用方式 MyRawSocket myRawSock; private void MainForm_Load(object sender, System.EventArgs e) { myRawSock = new MyRawSocket(IPAddress.Parse("192.168.1.111")); myRawSock.Receive += new MyRawSocket.ReceiveData(myRawSock_Receive); } void myRawSock_Receive(MyRawSocket.IPData ReceiveClass) { string Temp = ReceiveClass.OriginationAddress.ToString() + ":" + ReceiveClass.OriginationPort.ToString()+"\t"; Temp+=ReceiveClass.DestinationAddress.ToString() + ":" + ReceiveClass.DestinationPort.ToString()+"\t"; Temp+="{Size="+ReceiveClass.PackByte.Length.ToString()+"}"; this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(Temp); }); } private void button1_Click(object sender, System.EventArgs e) { myRawSock.Star(); }
|