Use libnet and libpcap to construct TCPIP protocol software

zhaozj2021-02-16  53

Using libnet and libpcap Software content: Overview What is the Libnet, LibPCapLibnet function library framework and use libpcap function library framework and use Libnet and libpcap: ARP routing MINITCPIP protocol Software System Frame: Two Discussion Private Protection Profile MINISocket User Programming Interface and Routine Conclusion Reference Reference About the author in? Linux? Zone also: Tutorial Tools & Product Code and Components Project Articles 褚蓬飞? (White_cpf@21cn.com) Chinese Academy of Sciences Software Technology Research Institute 2003 June 1st ???? In the Red? Hat? Linux8.0 Ethernet environment, use the libnet and the libpcap library to implement a TCP / IP protocol package for an Ethernet user-based single process: MiniTCPIP, which The software implements the basic communication function of the TCP protocol, and provides a debug interface and a interface function library MINISocket similar to the standard Socket interface to facilitate the user's debugging and application. The implementation of this user-state protocol package provides a good example for learning integrated use of Libnet and LibPCAP; through learning for this package, you can deepen the operation principle for TCP / IP protocols (especially in Ethernet). Understand; in addition, since this package is running in a single process, in a user environment, it has also brought great convenience to debugging and learning. Overview There are currently many different mature TCP / IP protocols, most of which are in the core implementation of the operating system, which is inevitable to improve the efficiency of TCP / IP protocol software, but it gives TCP / The IP protocol learns, research and commissioning has brought a lot of difficulties. Thus, if the efficiency problem implemented by the TCP / IP protocol software is not considered, a TCP / IP protocol software implemented in the application process is a certain meaning and value. This article constructs a single process TCP / IP protocol software: MiniTCPIP, and provides a socket interface function library: minisocket. When implementing this protocol software function library, the author chooses the use of libnet libpcap to implement this software in a user state, not only because this can avoid the inconvenience caused by some operating systems to develop in the underlying network, will be energetic Concentrate on the understanding of the protocol software itself; another reason, it is to provide an example for everyone to learn and integrate Libnet and LibPCAP. The LIBNET and LIBPCAP library and its use are first described, and a routine that implements its implementation ARP protocol - the implementation of the protocol is also included in MinitCPIP software, then gives the protocol software and sockets. The program implemented by the library, and analyzes some of the key technical issues involved in this paper. Finally, this implementation method has made a simple summary, pointing out some limitations of this implementation method. What is the Libnet, LibPCAP current a wide range of network security programs, tools and software are based on Socket design and development. Since the details of the network communication (such as the connection between two parties address / port, service type, transmission control, etc.) are often required to check, process, or control, data packet head analysis, and even truncation Connection, etc. must be implemented almost every network security program. In order to simplify the writing process of the network security program, improve the performance and robustness of the network security program, and make the code more easily reuse and transplant, the best way is to open / close the process of the most common and most compatible process, such as the opening / closing of the monitor , Data packet cut, data packet construction / transmission / reception, etc., is provided to developers in a way of API? Library.

In numerous API? Library, for network security tool development on the UNIX system platform, the most popular C? API? Library has libnet, libpcap, libnids, and libicmp. They provide different functional functions from different levels and perspectives, respectively. Make network developers to ignore the implementation of the network underlying detail, thus focusing on the design and development of the specific function of the program itself. Among them, the interface function provided by the Libnet mainly implements and encapsulates the construction and transmission of the packet. The interface function provided by LIBPCAP mainly implements and encapsulates the process related to the data package. With these interfaces of these C function libraries, network security tool developers can easily prepare a program with structuring strength, robust, and high portability. Therefore, these function libraries have great value in the development of network security tools. They have achieved extremely broad applications in the fields of Scanner, Sniffer, Firewall, IDS, and the famous TCPDUMP software, Ethereal software, etc., based on LibPCAP. developing. It should also be pointed out that due to its powerful, these function libraries are also used to construct the TCP / IP network program to attack the target host. However, the security of TCP / IP networks should not be built on the basis of baning everyone from using tools, first of all, must be an open network, this network should be safe in the case of using any tool. And robust. From this consideration, these tools are beneficial to facilitate the continuous improvement of existing network systems. The libnet function library framework and use libnet are a small interface function library, which is mainly written in C language, providing construction, processing, and transmission functions of low-level network datagrams. The development of Libnet is to establish a simple unified network programming interface to block the difference in low-level network programming of different operating systems, making programmers to concentrate on resolve key issues. His main features are: High-level interfaces: Libnet mainly writes portable use: libnet is currently running on operating systems such as Linux, FreeBSD, Solaris, WindowsNT, and provides a unified interface datagram constructor: Libnet provides one The constructor of the series TCP / IP data packets for easy users to use the datagram: LIBNET provides a series of secondary auxiliary functions, using these auxiliary functions to help users simplify those cumbersome programming work datagram: Libnet Allow users to select in two different datagram transfer methods. In addition, the libnet allows programs to obtain absolute controls for datagrams, some of which are not provided by traditional network program interfaces. This is also one of the charm of the Libnet. The libnet supports a variety of protocols in the TCP / IP protocol, such as its last version of Libnet1.0 supports 10 protocols, some new protocols, such as supporting IPv6 support. The latest version of Libnet is 1.1 version. In this version, the author makes these functions further package, and the user's use step has also been further simplified. Functions of initialization, management, release, etc., and calculation of checksums, without users directly intervene without users, making the LIBNET more convenient. The author also provides the method guidance based on old version-based applications to new versions. Using the basic steps for developing applications using libnet 1.1 Library and several critical functions: ??? 1.? Initializes libnet_t? * Libnet_init (int? INJECTION_TYPE,? CHAR? * Device,? Char? * Err_buf ); ?????? The function initializes the libnet function library, returns a libnet_t type descriptor to use the subsequent constructor to use in a function of sending a datagram. INJECTION_TYPE indicates the interface type used by the sending datagram, such as the data link layer or the original socket.

Device is a string of a network device name, which is "eth0" under Linux. If the function is incorrect, return NULL, and the error will be carried in the ERR_BUF string. ??? 2. • Data reporting ?????? LIBNET provides a wealth of datagram, which can construct a message of most protocols in the TCP / IP protocol family, but also provide some parameters. A more concise constructor of default value for users to choose. For example, libnet_autobuild_ipv4 (), etc. ??? 3. • Database Send INT? Libnet_write (libnet_t? * L); ?????? The function transmits the datagram described in the L. Success will return to the number of bytes sent, if it fails, returns -1. You can call libnet_geterror () to get the cause of the error ?? 4.? Exit VOID? LIBNET_DESTROY (libnet_t? * L); LibPCap function library framework and use libpcap English meaning? Packet? Capture? Library, ie packet capture function Library. The C function interface provided by the library can be used to capture the network interface (by setting the NIC to a mixed mode, can capture all the data reported by the interface, the target address is not necessarily the native) packet system development. The famous TCPDUMP is developed based on LibPCAP. The interface function provided by LIBPCAP mainly implements and encapsulates the process related to the data package. This library provides a consistent programming interface for different platforms, on the platform where libpcap is installed, written by libpcap, which is free cross-platform. Under Linux systems, libpcap can use BPF (Berkeley® Packet® Filter) packet capture mechanism to get high performance. Using the basic steps of the application of the libpcap function library and several key functions: ??? 1.char? * PCAP_LOOKUPDEV (char? * Errbuf) ?????? This function is used to return can be PcAP_Open_Live () Or PCAP_LOOKUPNET () Function calling network device name (a string pointer). If the function is wrong, return null and store the related error message in Errbuf. ??? 2.Int?pcap_lookupnet (CHARpter32 *Netp, BPF_U_INT32?MASKP ,?CHARpter32?MASKP ,?CHARpter32?MASKP ,?CHARpter32?MASKP ,?CHARpter32?Maskp ,?charpter ererrbuf) ?????? Get the network number and mask of the specified network device. NETP parameters and maskp parameters are BPF_U_INT32 pointers. If the function is wrong, return -1, and save the related error message in Errbuf. ??? 3.? Open the device PCAP_T? * PCAP_OPEN_LIVE (CHAR? * Device,? INT? SNAPLEN, INT? PROMISC,? INT? TO_MS, CHAR? * EBUF) ?????? Getting Used to capture network packets Packet capture descriptors. The Device parameter is the name of the network device that is specified. The SNAplen parameter defines the maximum number of bytes of capture data. Promisc specifies whether to place the network interface in a mixed mode. The TO_MS parameter specifies the timeout (ms). The EBUF parameter is used to pass the error message only when the PCAP_OPEN_LIVE () function error returns NULL. ??? 4. • Compile and set the filter int? PCAP_COMPILE (PCAP_T? * P,? Struct? BPF_PROGRAM? * FP, CHAR? * STR,? INT? OPTIMIZE,? BPF_U_INT32? NETMASK) ?????? The string specified by the STR parameter is compiled into the filter. FP is a pointer for a BPF_Program structure that is assigned in the PCAP_Compile () function. Optimize parameter control results code optimization. The Netmask parameter specifies the network mask of the local network.

INT? PCAP_SETFILTER (PCAP_T? * P,? Struct? BPF_PROGRAM? * fp) ??????? Specify a filter. The fp parameter is the BPF_Program structure pointer, which is usually taken from the PCAP_Compile () function call. Returns -1 when an error; returns 0 when successful. Caught the next packet ??? 5.? Caught the packet int? PCAP_DISPATCH (PCAP_T? * P,? INT? CNT, PCAP_HANDLER? Callback,? U_char? * User) ?????? Capture and process data package. The CNT parameter specifies that the function returns the maximum value of the packet processed. CNT = -1 represents all packets in a buffer. CNT = 0 represents all packets until one of the following errors: reads EOF; timeout reading. The Callback parameter specifies a callback function with three parameters. These three parameters are: a U_CHAR pointer passed from the PCAP_DISPATCH () function, a PCAP_PKTHDR structure pointer, and a U_CHAR pointer of a packet size. If success, return the number of bytes read. A zero value is returned if you read the EOF. Returns -1 when an error is incorrect, and the PCAP_PETERR () or PCAP_GETERR () function can be invoked. INT? PCAP_LOOP (PCAP_T? * P,? INT? CNT,? PCAP_HANDLER? CALLBACK,? U_CHAR? * user) ??????? Function is basically the same as the PCAP_DISPATCH () function, but this function is in CNT packets Returns when it is handled or an error, but the reading timeout will not return. And if the PCAP_OPEN_LIVE () function specifies a non-zero value timeout setting, then call the PCAP_DISPATCH () function, the PCAP_DISPATCH () function will return when the timeout occurs. The PCAP_LOOP () function will always run in a negative value, unless an error occurs. u_char? * PCAP_NEXT (PCAP_T? * P,? Struct? PCAP_PKTHDR? * H) ??????? Returns the U_CHAR pointer to the next packet. ??? 6.void? PCAP_CLOSE (PCAP_T? * P) ?????? Close the file corresponding to the P parameter and release the resource. ??? 7. Other auxiliary functions file? * PCAP_FILE (PCAP_T? * P) ?????? Returns the file name that is opened. INT? PCAP_FILENO (PCAP_T? * P) ?????? Returns the file description word number of the opened file. Integrated Libnet and LibPCAP: ARP routines use libnet and libpcap to construct powerful network analysis, diagnostics, and applications. A principle framework with universal integrated use libnet and libpcap, as shown in Figure 1: This section gives a simple routine for integrated application libnet and libpcap, which is to receive an ARP request report from a particular host. After the text, the ARP response message is issued to inform the MAC address corresponding to the IP address of the host request. This program implements a standard ARP protocol, but is different from the standard implementation method of the operating system core: This program utilizes libpcap to capture the data link layer captain, using libnet to package the data link layer, is to use Libnet and LibPCAP Construct a routine for TCP / IP protocol software.

The program is simple, but it is already possible to explain the integrated use of libnet and libpcap: / *? Tell? Destination? Host? WITH? Ip? 'Dstip'? That? The? Host? WITH? REQUEST? IP? 'Srcip'? IS? WITH? Mac? address? srcmac? *? author:? White? ?? 2003.5.15.? *? compile:? GCC? ARP.C? -lnet? -lpcap? -o? arp? * / # INCLUDE? "/ usr / include / libnet.h" #include? void? usage (char? *? eXename) {

Printf ("? Tell? Dstip? With? Dstmac? That? srcip? is? at? srcmac.? / n");

Printf ("? usage:?% s? -d? dstip? -s? srcip? -d? dstmac? -s? srcmac? / n", exename);

RETURN ?;

}

// Program input: from command line parameters

U_CHAR? IP_SRC [4], IP_DST [4];

U_CHAR? ENET_SRC [6], ENET_DST [6];

EXTERN? INT? MAC_STRTRTOCHAR6 (U_CHAR? *? ENET, CHAR? *? MACSTR); // converts the MAC address of the string format to 6 byte type R

INT? get_cmdline (int? argc, char? * argv []); // command line parameter processing function

INT? main (int? argc,? char? * argv []) {

???? il;

???? LIBNET_PTAG_T? T;

???? u_char? * packet;

???? u_long? packet_s;

???????? device [5] = "eth0";

????????? er errbuf [libnet_errbuf_size];

?????????filter_str [100] = "";

???? struct? bpf_program? fp; ?????? / *? hold? compiled? program ????? * /

?????????? * dev;

???? PCAP_T *? DESCR;

???? Struct? PCAP_PKTHDR? HDR; ????? / *? pcap.h ???? * /

???? u_char? *? packet;

???? bpf_u_int32? maskp; ?????????? / *? subnet? Mask ??????????????? * /

???? bpf_u_int32? netp; ?????????????? ip ??????????????? * /

???? int? promisc = 0; ????????????? / *? set? TO? PROMISC? Mode? * /

???? int? PCAP_TIME_OUT = 5;

???? int? C,? Ret;

???? u_long? i;

???? IF (get_cmdline (argc, argv) <= 0) {

USAGE (Argv [0]);

exit (0);

????}

???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

DEV? =? PCAP_LOOKUPDEV (Errbuf);

IF (dev? ==? null) {?

???? fprintf (stderr, "% s / n", errbuf);

???? RETURN? -1;

????}

???? RET = PCAP_LOOKUPNET (dev, & netp, & maskp, errbuf);

IF (RET == - 1) {

???? fprintf (stderr, "% s / n", errbuf);

???? RETURN? -1;

}

DESCR? =? PCAP_OPEN_LIVE (dev, bufsiz, promisc, pcap_time_out, errbuf); ???? IF (descr? ==? null) {

???? printf ("PCAP_OPEN_LIVE ():?% s / n", errbuf);

???? RETURN? -1;?

????}

Sprintf (Filter_Str, "ARP? and? (src? Net?% d.% d.% d.% d)", IP_DST [0], IP_DST [1], IP_DST [2], IP_DST [3]);

IF (PCAP_Compile (Descr, & FP, Filter_Str, 0, Netp)? ==? - 1) {

PRINTF ("Error? Calling? PCAP_COMPILE / N");?

RETURN? -1;

}

???? IF (PCAP_SETFILTER (DESCR, & FP)? ==? - 1) {?

???? printf ("error? setting? filter / n");?

???? RETURN? -1;

????}

While (1) {

Printf ("Wait? Packet: Filter:% S / N", Filter_STR);

Packet = PCAP_NEXT (DESCR,? & HDR);

IF (packet? ==? null) {

????

}

???? l? =? libnet_init (libnet_link_adv, device, errbuf);?

???? i? (l? ==? null) {

???????? fprintf (stderr,? "LIBNET_INIT ()? FAILED:?% s",? errbuf);

???????? EXIT (exit_failure);

????}

???? t? =? libnet_build_arp (

???????????? arphrd_ther, ?????????????????????????????????????????????????????????????????? *? Hardware? Addr? * /

???????????? ethertype_ip, ???????????????????????????? *? Protocol? Addr? * /

????????????? 6, ??????????????????????????????????????????????? ?? / *? Hardware? addr? size? * /

????????????? 4, ???????????????????????????? ?? / *? protocol? addr? size? * /

???????????? arpop_reply, ????????????????????????????? *? Operation? Type? * /

???????????? eNET_SRC, ??????????????????????????????? *? sender? Hardware? addr? * /

???????????? ip_src, ???????????????????????????? *? Sender? protocol? addr? * /

???????????? eNET_DST, ??????????????????????? *? target? Hardware? addr? * /

???????????? ip_dst, ????????????????????????????????????? *? Target? protocol? addr? * /

???????????? null, ?????????????????????????? *? payload? * /

????????????? 0, ?????????????????????????????????????????????????????????????????????????????????????????????????????????????? ?? / *? payload? size? * /

???????????? L, ?????????????????????????????????????? ?? / *? libnet? Handle? * / ????????????????????????????? ????????????? / *? libnet? id? * /

???? i? (t? ==? - 1) {

???????? fprintf (stderr,? "can't? build? ARP? HEADER:?% s / n",? libnet_geterror (l));

???????? goto? Bad;

????}

???? t? =? libnet_autobuild_ethernet (

????????????? eNET_DST, ?????????????????????????????? *? Ethernet? Destination? * /

???????????? ethertype_arp, ??????????????????????????? *? Protocol? Type? * /

???????????? l); ???????????????????????????? ?? / *? libnet? Handle? * /

???? i? (t? ==? - 1) {

???????? fprintf (stderr,? "can't? build? Ethernet? Header:?% s / n",? libnet_geterror (l));

???????? goto? Bad;

????}

???? c? =? libnet_adv_cull_packet (l,? & packet,? & packet_s);

???? i? (c? ==? - 1) {

???????? fprintf (stderr,? "libnet_adv_cull_packet:?% s / n",? libnet_getrror (l));

???????? goto? Bad;

????}

???? c? =? libnet_write (l);

???? i? (c? ==? - 1) {

???????? fprintf (stderr,? "Write? error:?% s / n",? libnet_geterror (l));

???????? goto? Bad;

????}

????

Bad:

???? LIBNET_DESTROY (L);

???? RETURN? (exit_failure);

}

???? LIBNET_DESTROY (L);

???? RETURN? (exit_failure);

}

INT? GET_CMDLINE (int? argc, char? * argv []) {

CHAR? C;

Char? string [] = "D: S: D: s: h";

???? while ((c? =? getopt (argc,? argv,? string))?! =? EOF) {

???????? IF (c == 'd')

????????????? * ((unsigned? int *) ip_dst) = (unsigned? int) inet_addr (OPTARG);

???????? ELSE? IF (c ==? 's')

???????????? * ((unsigned? int *) ip_src) = (unsigned? int) inet_addr (OPTARG);

???????? ELSE? IF (c == 'd')

???????????? Mac_STRTOCHAR6 (ENET_DST, OPTARG);

???????? ELSE? IF (c == 's')

???????????? Mac_STRTOCHAR6 (ENET_DST, OPTARG);

???????? ELSE? IF (c == 'h') ???????????? RETURN? 0;

???????? ELSE

???????????? RETURN? -1;

????}

RETURN? 1;

}

MinitCPIP Protocol Software System Framework:

Figure 3 and Figure 4 show a frame diagram of the MinitCPIP protocol software system. Among them, the MinitCPIP protocol software is implemented in a separate process. This process serves as a TCP / IP protocol software server to establish a C / S model to serve the application. Its communication uses a naming pipe to establish a C / S model. Any user's application process is used as a client to perform as a client, through the Minisocket library. Its communication model is shown in Figure 2.

[Figure 2? Use the pipe to establish a C / S model]

Once the protocol software process is run, the Libnet, LibPCAP, initializes the TCP / IP Connection Management Table (TCB), and the receiving and send buffer, open well-known FIFO, etc., then waiting for the client from sending (by well known FIFO) . After receiving the legal command, including establishing a connection, sending data, receiving data, turning off connection, and setting connection properties, etc., the corresponding analysis and processing is made. For example, according to the source IP specified in the command, the data on the network is started to monitor and receive data (as below, actually monitoring three file descriptors), and so on.

In order to facilitate monitoring and debugging the internal state of the protocol software, the protocol software simultaneously waits for the standard input device, and the protocol software will form an output of the standard output device according to the legal command of the standard input.

In addition to waiting for the client's command, the protocol software must wait for data from the network device at the same time in the standard input device waiting for the monitor command. In order to deal with the data of these different sources in the same process, the software is obtained by using the function interface INT? PCAP_FILENO (PCAP_T? * P) provided by libppcap, obtains the file descriptor of the opened network device file. After obtaining this descriptor, you can use the SELECT () function to use the SELECT () function to perform parallel with the pipeline file descriptor.

When the file description word of the network device file is readable, the software will call U_CHAR? * PCAP_NEXT (PCAP_T? * P,? Struct? PCAP_PKTHDR? * H) function to get the next captured packet.

The principles of the protocol software are as follows:

MAIN () {

Initialize libnet, libpcap; allocate reception, send buffer; initialization timer; etc.

While (1) {

IF (send buffer with data) {

send data

}

Call the select () function Wait for 3 file descriptors ready, these three file descriptors are: PCAP file descriptor, Watching a document descriptor, standard input file descriptor

IF (PCAP file descriptor is ready) {

Call the PCAP_NEXT () function to get the next captured packet

}

IF (Watching Document Descriptor is ready) {

Read data

According to the information in the TCB inside the process, analyze the TCP protocol specification

}

IF (standard input file descriptor ready) {

Read data

Analysis processing, such as feedback internal information to standard output file descriptor

}

IF (timeout) {

Overtime processing

}

}

}

As shown above, when a data packet on the network is received, the analysis process is performed according to the packet format such as TCP / IP protocol IP, TCP, and the received data is passed to the client application. When receiving the data packet of a known pipeline, the corresponding operation is performed according to the command type of the data packet, such as one of the commands -send commands, after receiving this command, then writing the following data Send buffers, in subsequent cycles, these data will be sequentially sent to the network. Communication in the Zhouzhi pipeline and the return pipeline adopts a custom protocol, which briefly introduces this. The final system is shown in the following two figures: wherein Figure 3 is an overall structure of the system at runtime, Figure 4 is a structure inside the protocol software process.

[Figure 3? System overall structure]

[Figure 4? Agreement software process internal structure]

The TCP / IP protocol data processing module is a set of functions, with a key data structure TCP table (TCB), etc., which is responsible for implementing the TCP / IP protocol.

Two discussions on the implementation of the protocol of MiniTCPIP

After years of development, the currently widely used standard TCP / IP software has been capable of supporting multiple physical devices such as Ethernet, serial links. The implementation discussed in this article is mainly focusing on Ethernet.

The following discussion focuses on the setting of the timer and two problems with the mutual exclusion of the operating system.

The actual TCP / IP protocol software is a very complex system with flow control and congestion control mechanism, which is generally completed by multiple system processes such as TCP / IP output, input processes, timer processes. An important basis for achieving these mechanisms is the setting and processing of the timer. This article is implemented in a single process, and it is difficult to achieve complex precision timing, so it is quite simplified on the timer. Among them, the TIME_WAIT status timing time in the TCP protocol state is a basic parameter. Once the MiniTCPIP runs, this parameter will not change, or can only be used to debug the purpose of debugging the destination by the standard input port; each TCP / IP connection The retransmission of the timer is established based on the reception effect of all the datagrams of the connection. The specific implementation is to set a minimum time interval parameter and a maximum time interval parameter. After the system is initialized, the minimum is retransmitted. After each timeout occurred (no dataginary report from the connection or no data report with an ACK flag and confirmed the correct number, the retransmission time is doubled, until the maximum is reached; if it is correct After receiving a number of datagrams, there is no timeout, and the retransmission timing time is half, until the minimum value is reached. The comparison result of whether the clock value of the last transmitted time clock is subtracted from the system current clock is derived by resending the time clock. The overflow time used by the SELECT () function takes the minimum value of all connected time dividers to ensure timely transmission packets. Such strategies are of course not high, but it has guaranteed the correct operation of the protocol software.

In addition, the MinitCPIP protocol software is implemented in the event of a standard TCP / IP protocol stack at the same time, and the principle of BPF is replicated instead of intercepting the data packets received by this machine. Therefore, the operating system also processes the received packets. If this problem is not handled, there will be some problems with each other with each other of the TCP / IP software within the operating system. For example, on the source main machine, if the specified source port has been opened, it will inevitably affect the normal running program, and finally leads to it properly. At the same time, when connecting to the standard TCP / IP protocol software on the remote target host, the operating system of this unit also receives the header of the target host, and discovers the IP address and port specified by this message. Not in the open port entry, the operating system believes that a non-legitable message is considered. Many operating systems The reaction of this event is to send a message with the RST flag, resulting in a reset of the target host. There are several possible solutions: this issue:

??? 1.

??? 2. If the target host also uses MiniTCPIP to implement TCP / IP communication, we can modify the definition of flag bit in standard TCP / IP datagram, such as ignoring all received RST logo. And when you need to send a reset datagram, you can replace other reserved flags.

??? 3. When the client is established, use an idle IP address of this segment as the source IP address. Such an operating system will consider that all datagrams that are sent to the IP address are not the native should receive, so that we do not need to react; however, our MinitCPIP can receive this datagram. Of course, for the distal target host to communicate with this "莫 须" IP address, there is a running process of an ARP protocol, sending the MAC address corresponding to all the requesting machines. A similar sample program has been provided in the above, and this function can be implemented slightly. This program can also be integrated in MinitCPIP.

MiniTCPIP uses the third solution, the network card must be set in the mixed mode. In this way, the CPU usage will be higher, and the probability of packet loss will increase, and the efficiency will fall. Therefore, MiniTCPIP is only available for small loads.

Private agreement introduction

The service provided by MiniTCPIP provides a C / S model. The model map of this service is shown in Figure 2, see "Unix Environment Advanced Programming" for details. Any user's application process is performed by using the MINITCPIP to perform through the Minisocket library, while the Minisocket is performed by a custom private protocol. This private agreement is implemented in the C / S communications established by the user process and the protocol software process.

Named pipelines are already reliable local process communication mechanisms, but the transfer between Minisocket and MinitCPIP protocol software is more than just send and receive byte streams, but also controls to Socket, such as application SOCKET number, establish TCP connection, close Control commands such as TCP connections, so you must design a simple communication protocol to meet specific communication requirements. Specifications for detailed communication protocols This is no longer listed.

Pipe communication generally does not have a loss of packets and disresal issues, so this protocol only needs to be responsible for packets (using esca, and data length and checksum) and distinguish different types of packets (packets, Control package). If the pipeline operation itself occurs, the program is abnormally exited. The following figure 5 is a datagap format used in this private protocol: the specific data packet is detected by the character fill scheme, such as the above-in-theme relationship is not large, and this is no longer detailed here.

[Figure 5? Private Protocol Data Dance Format] Where the first byte of the data is always command type, as the name suggests, the command type defines the type of all the communication data between the application and the protocol software, mainly including two types of commands , That is, the control command and the information transfer command, the control command is used to control the status of the TCP connection, etc., the information command is the data that the client is really transferred to the retread to the client. The specific list of command formats is no longer detailed.

MINISocket user programming interface and routine

The client communicates by calling the Minisocket interface, which encapsulates the cumbersome details of the private protocol, providing a simple unified function library similar to the standard Socket interface to users. The MINISocket interface function library currently implemented is quite simple, and the function is also limited, including the implementation of the TCP protocol client. When writing a client application, users only need to know a few of several data structures and function prototypes:

Struct? mini_sock {?

???????????????????? u8? type; // = tcp? or? udp

???????????????????? u32? DIP; // Destination? ip

???????????????????? u32? dport; // destination? Port

???????????????????? u16? SIP; // source? ip

??????????????????? u16? Sport; // source? port

??????????????????? ......

??????????????}

This data structure is defined in mini_socket.h, including all parameters of the TCP connection that the user needs to be established.

User Function Interface Definition:

INT? mini_socket (STRUCT? Mini_Sock *)

This function creates a socket, and struct? Socket * must fill out the parameters related to the Socket you want to create.

The successful return value is actually a client-specific FIFO file descriptor for the protocol software writes data. This allows the user to implement the processing of multiple input and output of the single process using the standard SELECT () function. However, the read and write operations on this file descriptor must use the functions provided by Minisocket to be properly performed.

INT? mini_connect (int? socket)

???? This function is used to notify the protocol software to establish a TCP connection by shaking hands three times with the target host.

INT? mini_recv (int? Socket,? char *? buf, int? *? buflen

???? This function receives data from the specified Socket

INT? mini_send (int? Socket, Char * BUF, INT? BUFLEN)

???? This function sends the specified data to the socket

INT? mini_close (int? Socket)

???? This function is used to notify the protocol software to close the specified Socket connection

A simple routine for implementing the Echo service using this Agreement Software Function is as follows:

/ ************************************************** **

*? Simple? Tcp? Echo? Client? Using? Libnet? And? Libpcap? And? Mini_socket.c

*? file: ????? miniecho.c

*? Date: ???? 2003.5.

*? Author: ??? White? CPF

*? Compile: ?? GCC? -wall? -lpcap? -lnet? miniecho.c? mini_socket.c? -o? miniecho?

*? Run: ????? readhat? 8.0? You? Must? Be? Root? And? Run? Ifconfig? To? See? Eth0? OK

*********************************************************** *** /

#include?

#include?

#include? "mini_socket.h" #define? uchar? unsigned? char

#define? Maxbufflen? 2048

CHAR? BUF [Maxbufflen];

Int? buflen;

CHAR? Recvbuf [Maxbufflen];

Int? recvedlen;

INT? main (int? argc, char? * argv []) {

int? Ret;

Int? i;

CHAR? SIP [40] = "169.254.159.112";

CHAR? Sport [10] = "7777";

CHAR? DIP [40] = "169.254.159.111";

CHAR? DPORT [10] = "5000";

Struct? Socket? TI;

Int? s;

Ti.SIP = INET_ADDR (SIP);

Ti.dip = INET_ADDR (DIP);

Ti.Sport = (unsigned? short) atoi (SPORT);

Ti.dport = (unsigned? short) ATOI (DPORT);

s = mini_socket; & ti;

IF (s <0) {

Printf ("Mini_Socket ()? error / n");

RETURN? 0;

}

RET = mini_connect (s); // connect? to? tcpip? using? TCP? THREE? TIME? HANDSHAKING

IF (RET <0) {

Printf ("" mini_connect ()? error / n ");

RETURN? 0;

}

While? (1) {

// Get? INPUT? From? stdin, ?? quit? When? Eof? or? "myquit!"? Input

IF (FGETS (BUF,? sizeof (buf) ,? stdin) == 0) ?? Break;

IF (strcmp (buf, "myquit!") == 0) ??????? Break;

Ret = mini_send (S, BUF, Strlen (BUF));

IF (RET <= 0) {

Printf ("" mini_send ()? RETURN?% D / N ", RET);

Break;

}

Ret = mini_recv (s, recvbuf, & recvedlen);

IF (RET <= 0) {

Printf ("" mini_rec ()? RETURN?% D / N ", RET);

Break;

}

Recvbuf [recvEDlen] = 0;

Printf ("Recved [% D? Bytes]:% S / N", Recvedlen, Recvbuf;

}

Mini_close (s); // close? tcpip? using? TCP? Three? Time? Handshaking

}

in conclusion

This article implements a single process TCP / IP protocol software: MiniTCPIP in the Linux environment by using the currently popular Libnet and LibPCAP function library: MINITCPIP, and provides a call interface: minisocket, through this interface, you can create TCP / IP Application of the agreement.

The MinitCPIP protocol software implemented in this article has only the smallest TCP / IP communication function, and the efficiency is also very general. However, as a learning of Libnet, LibPCAP, learning TCP / IP software in Ethernet implementation principles, this project has a certain value. In addition, the protocols related to this scheme are clear, which can be imagined, can be imagined, and codes that are unrelated to the environment in Minisocket can be easily transplanted to currently used embedded devices On the web application, this is another consideration for writing this article. Due to time tension, many of the implementation of MinitCPIP protocol software has continued to consider, and the author itself is also in the process of learning, and the mistakes are inevitable. If this article can learn Libnet, Libpcap, TCPIP, the author Getting is pleased. At the same time, I hope that everyone can give criticism and finger, with a joint increase.

Reference resource

???? *? www.tcpdump.org

???? *? www.packetfactory.net/libnet

???? *? "Unix Environment Advanced Programming"? Mechanical Industry Press? February 2000? W.RICHARD? Stevens

???? *? "Internet interconnection with TCP / IP? Volume 2: Design, implementation and internal composition" Electronic Industry Press? 1998? Dougles? E.COMER? DAVID? L.Stevens In

???? *? "A TCP debugging system design and implementation"? Zhang Wei? Xiong Yongqiang? Wu Jianping? Research Institute of Computer System Network, Tsinghua University

About author

蓬飞, male, born in 1976. In 1998, Qinghua University graduated into the Technical Center of Qingdao Hisense Group. During the 863 item -306 project - Digital home information system home gateway research and development work. In 2002, I entered the Chinese Academy of Sciences Software Technology Research Institute Learning, Research Direction: Multimedia Communication and Network Technology. You can contact it with? White_cpf@21cn.com.

转载请注明原文地址:https://www.9cbs.com/read-17828.html

New Post(0)