Use libnet and libpcap to construct TCPIP protocol software

zhaozj2021-02-16  51

Use libnet and libpcap to construct TCP / IP protocol software

content:

Overview What is the Libnet, LibpCapLibnet function library framework and use libpcap function library framework and use integrated libnet and libpcap: ARP routine Minitcpip protocol software system framework: Two-point discussion for Privacy Private Protocol ISOCKET User Programming Interfaces and routines Conclusion Reference About the author

In the Linux area:

Tutorial Tools & Product Codes and Component Project Articles

蓬飞 (White_cpf@21cn.com) Institute of Software Technology, Chinese Academy of Sciences, June 1, 2003

In the Red Hat Linux 8.0 Ethernet environment, the TCP / IP protocol package of Ethernet user-based single-process is implemented using the libnet and libppcap library: MiniTCPIP, the software implements the basic communication function of the TCP protocol, and A debug interface is provided and a interface function library MINISocket similar to the standard socket interface for 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 packaged, and it is provided to developers in the way API Library. In numerous API Library, for network security tools 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. The basic steps of using libnet1.1 function library development applications and several key functions are introduced below: Initialization

LIBNET_T * LIBNET_INIT (INT INJECTION_TYPE, CHAR * Device, Char * Err_buf);

This 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. The structure of the datagram provides a rich constructor of the datagram, which can construct a message of most protocols in the TCP / IP protocol, and provide some more concise constructor for certain parameters for user selection. . For example, libnet_autobuild_ipv4 (), etc. Data report

INT LIBNET_WRITE (libnet_t * L);

This function puts on the network described in the Du. Success will return to the number of bytes sent, if it fails, returns -1. You can call libnet_geterror () to get an error reason to exit

Void libnet_destroy (libnet_t * L);

Libpcap function library framework and English means using libpcap, Packet Capture Library, 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 the Linux system, libpcap can use the BPF (Berkeley Packet Filter packet capture mechanism to get high performance. Using the basic steps of the application of the libpcap function library development application and several critical functions: char * PCAP_LOOKUPDEV (Char * Errbuf)

This function is used to return a network device name (a string pointer) that can be called by the PCAP_OPEN_LIVE () or PCAP_LOOKUPNET () function. If the function is wrong, return null and store the related error message in Errbuf.

INT PCAP_LOOKUPNET (Char * Device, BPF_U_INT32 * NETP, BPF_U_INT32 * MASKP, CHAR * Errbuf)

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. Open the device

PCAP_T * PCAP_OPEN_LIVE (Char * Device, Int Snaplen, Int Promisc, int to_ms, char * ebuf)

Get a data packet capture descriptor used to capture a network packet. 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. Compile and set the filter

INT PCAP_COMPILE (PCAP_T * P, Struct BPF_PROGRAM * FP, CHAR * STR, INT OPTIMIZE, BPF_U_INT32 NETMASK)

Compile the string specified by the STR parameter 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. Catch the next packet to capture the packet

INT PCAP_DISPATCH (PCAP_T * P, INT CNT, PCAP_HANDLER CALLBACK, U_CHAR * USER)

Capture and process the packet. 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 returns when the CNT packet is processed or an error, but the read 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.

Void PCAP_Close (PCAP_T * P)

Turn off the file corresponding to the P parameter and release the resource. 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 that is 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 comprehensive method of 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 CPF 2003.5.15.

* Compile: GCC ARP.C -LNET -LPCAP -O ARP

* /

#include "/usr/include/libnet.h"

#include

Void usage (char * exENme) {

Printf ("TELL DSTIP with DSTMAC That Srcip IS At Srcmac. / N");

Printf ("USAGE:% s -d Dstip -s srcip -d Dstmac-Srcmac / N", Exename);

Return;

}

// Program input: from command line parameter u_char ip_src [4], ip_dst [4];

U_CHAR ENET_SRC [6], ENET_DST [6];

Extern int mac_strtochar6 (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 []) {

LIBNET_T * L;

LIBNET_PTAG_T T;

U_CHAR * PACKET;

u_long packet_s;

Char Device [5] = "eth0";

CHAR ERRBUF [LIBNET_ERRBUF_SIZE];

CHAR FILTER_STR [100] = "";

Struct BPF_Program FP; / * Hold Compiled Program * /

Char * 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 prosisc 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_COMP, 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) {Continue;

}

L = libnet_init (libnet_link_adv, device, errbuf);

IF (l == NULL) {

FPRINTF (stderr, "libnet_init () failed:% s", errbuf);

EXIT (exit_failure);

}

T = LIBNET_BUILD_ARP (

Arphrd_ether, / * 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 * /

0); / * LIBNET ID * /

IF (t == -1) {

FPRINTF (stderr, "can't build arp header:% s / n", libnet_getrror (l));

Goto Bad;

}

T = LIBNET_AUTOBUILD_ETHERNET

eNET_DST, / * Ethernet Destination * /

Ethertype_arp, / * protocol type * /

l); / * Libnet Handle * /

IF (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);

IF (c == -1) {

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

Goto Bad;

}

C = Libnet_Write (L);

IF (c == -1) {

FPRINTF (stderr, "write error:% s / n", libnet_getrror (l)); goto bad;

}

CONTINUE;

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 Frame: Figure 3 and Figure 4 is 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. 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 these different sources of data in the same process, the software obtains the file descriptor of the open network device file by using the function interface INT PCAP_FILANO (PCAP_T * P) provided by libppcap. 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, the software will call the 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. 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-point discussion on the implementation of MinitCPIP has been developed by many years. The currently widely used standard TCP / IP software has been able to support Ethernet, serial links and other physical devices. The implementation discussed in this article is mainly concentrated in Ethernet. Above. 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: because the platform uses the Linux system for open source code, it is considered that the TCP software implementation section in the kernel (TCP software is submitted to the application process to the application process is filtered to the application process) to the illegal packet Default behavior. If you also use MinitCPIP to implement TCP / IP communication on the target host, we can modify the definition of flag bit in standard TCP / IP datagram, such as ignoring all received RST logo, and sending reset When the data is reported, you can replace other reserved signs. When the client is established, the IP address of an idle this network segment is used 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. Profile Profile MinitCPIP The service provided by the client uses a C / S model. The model map of this service is as shown in Figure 2, see "Unix Environment Advanced Programming". 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. Among them, the first byte of the data domain is always command type, as the name suggests, command type defines the type of all communication data between the application and protocol software, mainly including two types of commands, the control command and information transmission command, control The command is used to control the status of the TCP connection, etc., the information command is the data that the client really wants to transfer the return to the client. The specific list of command formats is no longer detailed. The MINISocket user programming interface and routine client communicates with MiniSocket interface by calling the Minisocket interface. This interface encapsulates a cumbersome detail of private protocols, providing a simple unified library similar to a 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 udpu32 dip; // destination ip

U32 Dport; // Destination Port

U16 SIP; // Source IP

U16 Sport; // Source Port

......

}

This data structure defines that in Mini_Socket.h, all parameter user function interface definitions of the TCP connection that the user needs to be established:

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 runifffig to see Eth0 OK

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

#include

#include

#include "mini_socket.h"

#define uchar unsigned char

#define maxbuflen 2048

Char buf [maxbuflen];

Int buflen;

Char recvbuf [maxbuflen];

Int recvedlen;

INT Main (int Argc, char * argv []) {

int R;

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_RECV () 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

}

Conclusion This article implements a single process TCP / IP protocol software: MiniTCPIP in the Linux environment by using the currently popular Libnet and LibPCAP library: Minitcpip, and provides a call interface: minisocket, through this interface, you can create TCP / IP protocol application. 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" Machine Industry Press W.Richard Steve W.Richard Stevers W.Richard Stevers, "Internet Interconnect, INTVEN, TCP / IP): Design, Implementation and Internal Composition "2nd Edition Electronic Industry Press 1998 DOUGLES E.COMER David L.Stevens," a TCP debugging system design and realization "Zhang Yu Xiong Yongqiang Wu Jianping Tsinghua University Computer System Network Research Institute

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

New Post(0)