When talking about socket programming, you may think of QQ and IE. That's right. Many other network tools, such as P2P and NetMeeting, are implemented at the application layer using socket. Socket is a network programming interface that is implemented on the network application layer. Windows Socket includes a set of system components that fully utilize the features of Microsoft Windows message driver. The Socket Specification Version 1.1 was released in January 1993 and is widely used in later Windows 9x operating systems. Socket Specification Version 2.2 (its version on Windows is Winsock2.2, also known as Winsock2) was released in May 1996. Windows NT 5.0 and later versions support Winsock2. In Winsock2, supports original sockets of multiple transmission protocols, overlapping I/O models, and service quality control. This article introduces some programming of the original Socket (Raw Socket) implemented by C # in Windows Sockets and the network packet Monitoring Technology Based on this. Compared with Winsock1, Winsock2 supports the Raw Socket type most obviously. Using Raw Socket, you can set the NIC to the hybrid mode. In this mode, we can receive the IP packet on the network, of course, for the purpose of not the local IP packet, through the original socket, we can also more freely control the various protocols in Windows, it can also control the underlying transmission mechanism of the network. In this example, the RawSocket class is implemented in the nbyte. BasicClass namespace, which includes the core technology for implementing packet monitoring. Before implementing this class, you need to write an IP header structure to temporarily store some information about network packets: [StructLayout (LayoutKind. Explicit)] Public struct IPHeader { [FieldOffset (0)] public byte ip_verlen; // I4-bit Header Length + 4-bit IP version number [FieldOffset (1)] public byte ip_tos; // 8-bit service type TOS [FieldOffset (2)] public ushort ip_totallength; // The total length of a 16-bit data packet (in bytes) [FieldOffset (4)] public ushort ip_id; // 16-bit ID [FieldOffset (6)] public ushort ip_offset; // 3-Bit Flag [FieldOffset (8)] public byte ip_ttl; // 8-bit TTL [FieldOffset (9)] public byte ip_protocol; // 8-bit protocol (TCP, UDP, ICMP, Etc .) [FieldOffset (10)] public ushort ip_checksum; // 16-bit IP header checksum [FieldOffset (12)] public uint ip_srcaddr; // 32-bit source IP address [FieldOffset (16)] public uint ip_destaddr; // 32-bit destination IP address } In this way, when each packet arrives, you can use forced type conversion to convert the data stream in the packet into IPHeader objects. The following describes the RawSocket class. At the beginning, several parameters are defined, including: Private bool error_occurred; // whether an error occurs when the socket receives the packet Public bool KeepRunning; // whether to continue Private static int len_receive_buf; // The length of the data stream. Byte [] receive_buf_bytes; // received bytes Private Socket socket = null; // declare a Socket There is also a constant: Const int SIO_RCVALL = unchecked (int) 0x98000001); // listen to all data packets The SIO_RCVALL indicates that RawSocket receives all data packets. It will be used in later IOContrl functions. In the following constructor, initialization of some variable parameters is implemented: Public RawSocket () // Constructor { Error_occurred = false; Len_receive_buf = 4096; Receive_buf_bytes = new byte [len_receive_buf]; } The following function creates RawSocket and binds it to the endpoint (IPEndPoint: local IP address and port: Public void CreateAndBindSocket (string IP) // create and bind a socket { Socket = new Socket (AddressFamily. InterNetwork, SocketType. Raw, ProtocolType. IP ); Socket. Blocking = false; // set the non-Blocking status of the socket. Socket. Bind (new IPEndPoint (IPAddress. Parse (IP), 0); // Bind a socket If (SetSocketOption () = false) error_occurred = true; } There are three parameters in socket = new Socket (AddressFamily. InterNetwork, SocketType. Raw, ProtocolType. IP) when creating a socket: The first parameter is to set the address family. The description on MSDN is "addressing scheme for specifying the Socket instance to resolve the address". When you want to bind the Socket to the IP endpoint, interNetwork members need to be used, that is, the address format of IP version 4. This is also an addressing solution (AddressFamily) adopted by most socket programming today ). The socket type set by the second parameter is the Raw type we use. SocketType is an enumeration data type. The Raw socket type supports access to the basic transmission protocol. Use SocketType. raw. You can not only use the Transmission Control Protocol (Tcp) to communicate with User Datagram Protocol (Udp), but also use the Internet message Control Protocol (Icmp) and Internet Group Management Protocol (Igmp). At the time of sending, your application must provide the complete IP header. The IP header and option of the received datagram remain unchanged when it is returned. The third parameter sets the protocol type. The Socket class uses ProtocolType to enumerate the data type and notifies the Windows Socket API of the requested protocol. The IP protocol is used here, so the ProtocolType. IP parameter must be used. The CreateAndBindSocket function has a custom SetSocketOption function, which is different from the SetSocketOption function in the Socket class. Here we define the SetSocketOption with IO control. Its definition is as follows: Private bool SetSocketOption () // sets raw socket { Bool ret_value = true; Try { Socket. SetSocketOption (SocketOptionLevel. IP, SocketOptionName. HeaderIncluded, 1 ); Byte [] IN = new byte [4] {1, 0, 0, 0 }; Byte [] OUT = new byte [4]; // In the low-Level operation mode, it is critical to accept all data packets. You must set the socket to raw and IP Level for the SIO_RCVALL operation. Int ret_code = socket. IOControl (SIO_RCVALL, IN, OUT ); Ret_code = OUT [0] + OUT [1] + OUT [2] + OUT [3]; // synthesize four 8-bit bytes into a 32-bit integer If (ret_code! = 0) ret_value = false; } Catch (SocketException) { Ret_value = false; } Return ret_value; } When setting the socket option, the socket must contain an IP header. Otherwise, the IP header structure cannot be filled or the packet information cannot be obtained. Int ret_code = socket. IOControl (SIO_RCVALL, IN, OUT); is the most critical step IN the function, because IN windows, we cannot use the Receive function to Receive raw socket data. This is because, all IP packets are first submitted to the system core and then transmitted to the user program. When a raws socket packet (such as syn) is sent, the core does not know, there is no record of this data being sent or established by the connection. Therefore, when the remote host responds, the system core will discard all these packages and thus cannot access the application. Therefore, you cannot simply use the receive function to receive these data packets. To receive data, you must use sniffing to receive all the passed data packets, and then filter them, leaving the data that meets our needs. You can set SIO_RCVALL to receive packets from all networks. Next we will introduce the IOControl function. MSDN explains that it sets sockets to a low-level operation mode. How can I perform a low-level operation? In fact, this function is similar to the WSAIoctl function in the API. The WSAIoctl function is defined as follows: Int WSAIoctl ( SOCKET s, // a specified SOCKET DWORD dwIoControlCode, // control the operation code LPVOID lpvInBuffer, // pointer to the input data stream DWORD cbInBuffer, // size of the input data stream (bytes) LPVOID lpvOutBuffer, // pointer to the output data stream DWORD cbOutBuffer, // size of the output data stream (bytes) LPDWORD maid, // point to the number of output byte streams LPWSAOVERLAPPED lpOverlapped, // point to a WSAOVERLAPPED Structure LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // point to the routine executed when the operation is complete ); The IOControl function of C # is not as complex as the WSAIoctl function. It only includes three parameters: control operation code, input byte stream, and output byte stream. However, these three parameters are sufficient. The function defines a byte array: byte [] IN = new byte [4] {1, 0, 0, 0} is actually a DWORD or Int32 with a value of 1, also byte [] OUT = new byte [4]; also, it is integrated with an int, as the value pointed to by the lpcbBytesReturned parameter in the WSAIoctl function. Because errors may occur when setting SOCKET options, you need to use a value to pass the error mark: Public bool ErrorOccurred { Get { Return error_occurred; } } The following functions receive data packets: // Parse the received data packet to form the PacketArrivedEventArgs event data Class Object and trigger the PacketArrival event 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 (); // new network packet Information Event Fixed (byte * fixed_buf = buf) { IPHeader * head = (IPHeader *) fixed_buf; // sets the data stream to an IPHeader structure. E. HeaderLength = (uint) (head-> ip_verlen & 0x0F) <2; Temp_protocol = head-> ip_protocol; Switch (temp_protocol) // extract protocol type { 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; // extract the IP protocol version E. IPVersion = temp_version.ToString (); // The following statement extracts other parameters in the PacketArrivedEventArgs object 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; // Assign the IP header in the buf to IPHeaderBuffer in PacketArrivedEventArgs Array. Copy (buf, 0, e. IPHeaderBuffer, 0, (int) e. HeaderLength ); // Assign the package content in the buf to MessageBuffer in PacketArrivedEventArgs Array. Copy (buf, (int) e. HeaderLength, e. MessageBuffer, 0, (int) e. MessageLength ); } // Trigger the PacketArrival event OnPacketArrival (e ); } We have noticed that in the above function, we use the so-called Insecure code like pointer, it can be seen that the original operations such as pointer and shift operations in C # can also bring programming convenience to the programmer. Declare the PacketArrivedEventArgs class object in the function, so that the data packet information can be transmitted through the OnPacketArrival (e) function through events. The PacketArrivedEventArgs class is a nested class in the RawSocket class. It inherits the system Event class and encapsulates information contained in other data headers, such as the IP address, port, and Protocol of the data packet. In the function that starts receiving data packets, we use the asynchronous operation method. The following function enables the asynchronous listening interface: Public void Run () // start listening { IAsyncResult ar = socket. BeginReceive (receive_buf_bytes, 0, len_receive_buf, SocketFlags. None, new AsyncCallback (CallReceive), this ); } Socket. the BeginReceive function returns an asynchronous operation interface, and declares the asynchronous callback function CallReceive in the BeginReceive function, and transmits the received network data stream to receive_buf_bytes, in this way, an asynchronous callback function with interface parameters for asynchronous operations can continuously receive data packets: Private void CallReceive (IAsyncResult ar) // asynchronous callback { Int received_bytes; Export ed_bytes = socket. EndReceive (ar ); Receive (receive_buf_bytes, received_bytes ); If (KeepRunning) Run (); } This function receives a new data packet when it suspends or ends asynchronous reading. This ensures that every data packet can be detected by the program. The following describes how to declare a proxy event handle to communicate with the outside world: Public delegate void PacketArrivedEventHandler (Object sender, PacketArrivedEventArgs args ); // Event handle: the event is triggered when the package arrives. Public event PacketArrivedEventHandler PacketArrival; // declare the time handle Function In this way, the data packet information can be obtained. the asynchronous callback function can improve the efficiency of receiving data packets and transmit the packet information to the outside world through proxy events. Since we can pass all the packet information out, we can analyze the data packet. :) However, the RawSocket task is not complete yet. In the end, do not close the socket: Public void Shutdown () // close raw socket { If (socket! = Null) { Socket. Shutdown (SocketShutdown. Both ); Socket. Close (); } } The RawSocket class obtains information in the package by constructing an IP header, and receives data packets through an asynchronous callback function, the time proxy handle and custom data packet information events are used to send data packet information, so as to monitor network data packets, in this way, we can add some functions to analyze data packets. |