Raw Socket programming for network packet monitoring

Source: Internet
Author: User

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; <

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.