C + + captures the IP packet of the native network card and resolves its implementation

Source: Internet
Author: User

Programming Requirements: Capture the IP packet of the native network card to resolve the captured IP packet. The following fields must be output: Version number, total length, flag bit, slice offset, protocol, source address, and destination address.

The TCP/IP protocol defines a packet that is transmitted over the Internet, called an IP datagram (IP Datagram). This is a hardware-independent virtual package, consisting of the header and the data. The first part of the header is a fixed length, a total of 20 bytes, is required for all IP datagrams. The fixed part of the header is followed by some optional fields whose length is variable. Let's look at the format of the IP packet:

Specific instructions:

via the slice offset value

Description of each field


IP protocol version number, IPv4 This field value is 4, IPv6 this field value is 6

First Minister

value range 5 (0101) ~15 (1111),  units for 4 bytes , including fixed and optional parts,  so the header is 60 bytes long,  The shortest is 20 bytes (excluding options and padding parts);

service type

length is 8 bits (because the field has been discarded without,  so do not consider)

 service type (to s) (8 bit) field includes a 3 bit priority sub-field (values can be from 000-111 all values), 4 bit to S subfield and 1 bit unused bit but must be set to 0 

The field length is 16 bits,  in bytes,  total length contains ip Head and Data section,  ip datagram Maximum length is 65535 bytes ,  but be careful not to exceed the length of the MTU


16-bit length,  uniquely identifies a datagram that can be used as a counter,  the value of each packet sent,  if the datagram is fragmented, The identity of each shard is the same,  each shard shares an identification number


3-bit flag the first bit does not use,  No Shard ;   third MF ( More fragment more shards Span style= "Color:rgb (0,255,0)"), indicates if there are more shards,  if the bit is 1,  then there is a shard,  the last one MF is 0

slice offset

survival time (TTL)

The number of routers .  value 0~255, each through a router, The  ttl value is reduced by 1, the,  is discarded at 0 o'clock and the ICMP packet is sent to notify the source host,  ttl can avoid the datagram looping between the routers continuously (tranceroute the implementation principle of the program)

protocol type

ip layer ,   In the process of,  the protocol stack knows which protocol to give the upper layer to handle,  such as 1 for icmp, 2 igmp, 6 for tcp, 17 for UDP, and so on.

header checksum

ensures data integrity at the data header, but the checksum does not include the data section. This is done for two purposes: one is that all high-level protocols that encapsulate data in IP packets contain checksums that cover the entire data, so there is no need for the IP datagram to verify the portion of the data it hosts. The second is that each router, the IP datagram head to change (such as TTL), and the data part of the same, so that only the change in the head to verify, obviously will not waste too much time. In order to reduce the computational time, the CRC check code is generally not used, but a simpler internet checksum (internet checksum) is adopted.

Options and Fills

The variable portion of the header is added to increase the functionality of the IP datagram, such as support for troubleshooting, Measurement and security, options ranging from 1 to 40 bytes, depending on the selected item (option is 4 byte integer multiple, otherwise 0 padding); However, this increases the cost of processing data per router, in fact, these options are rarely used, many routers do not consider the IP Header option field;

Here, after figuring out the structure of the IP packet, the rest is the basic socket programming pattern, just a few options to set.

See the code in detail, with specific notes:

#define _crt_secure_no_warnings#include <iostream> #include <winsock2.h> #include <windows.h># Include <string.h> #include <mstcpip.h> #pragma comment (lib, "Ws2_32.lib") using namespace std;//      IP header typedef struct TIPPACKHEAD{BYTE Ver_hlen; IP protocol version and IP first ministerial degree.       High 4-bit version, low 4-bit head length (in 4bytes) BYTE Bytos; Service type word Wpacketlen; Total IP packet length. Includes the header, in bytes. [Big endian]    WORD wsequence; Identification, typically incrementing the ordinal of each IP packet. [Big Endian]union{word flags;//Mark WORD fragof;//segment offset};         BYTE Byttl; Survival time BYTE Byprotocoltype;    protocol type, see Protocol_type definition word wheadchecksum;         IP header Checksum [Big Endian]dword dwipsrc;         Source Address DWORD Dwipdes;          Destination address byte Options; option} ip_head;int cnt;int Decodeip (char *buf, int len) {int n = len;if (n >= sizeof (Ip_head)) {Ip_head Iphead;iphead = * ( ip_head*) buf;cout << "<<cnt++<<" IP packet Information: "<< endl;cout <<" protocol version: "<< ( Iphead.ver_hlen >> 4) << endl;cout << "header length:" << ((Iphead.ver_hlen & 0x0f) << 2) << endl;//Unit is 4 bytes cout << "Service type: Priority:" << (Iphead.bytos >> 5) << ", Servi CE: "<< ((Iphead.bytos >> 1) & 0x0f) << endl;cout <<" IP packet total length: "<< ntohs (iphead.wpacketl EN) << Endl; Network byte order to host byte order cout << Identity: << ntohs (iphead.wsequence) << endl;cout << "flag bit:" << "df=" < < (Iphead. Flags >>) & 0x01) << ", mf=" << ((Iphead. Flags >>) & 0x01) << endl;cout << "Slice offset:" << (Iphead. Fragof & 0x1fff) << endl;cout << "life cycle:" << (int) iphead.byttl << endl;cout << "protocol type:" &L t;< Int (iphead.byprotocoltype) << endl;cout << "header checksum:" << ntohs (iphead.wheadchecksum) << Endl;cout << "Source address:" << inet_ntoa (* (in_addr*) &iphead.dwipsrc) << endl;cout << "Destination Address:" < < Inet_ntoa (* (in_addr*) &iphead.dwipdes) << endl;cout << "============================================================== "<< Endl << Endl;} return 0;} void Autowsacleanup () {:: WSACleanup ();} int main () {int n; Wsadata wd;n = WSAStartup (Makeword (2, 2), &AMP;WD); if (n) {cout << "WSAStartup function Error! "<< endl;return-1;} Atexit (autowsacleanup);//create Socketsocket sock = socket (af_inet, Sock_raw, ipproto_ip); if (sock = = Invalid_socket) {cout & lt;< WSAGetLastError (); return 0;} Gets the native address char name[128];if ( -1 = = gethostname (name, sizeof (name))) {closesocket (sock); cout << WSAGetLastError (); return 0;} struct Hostent * phostent;phostent = gethostbyname (name);//Bind the address to the socket handle sockaddr_in addr;addr.sin_family = af_inet; ADDR.SIN_ADDR = * (in_addr*) phostent->h_addr_list[0]; Ipaddr.sin_port = 8888; Port, IP layer port can be arbitrarily filled if (Socket_error = = bind (sock, (SOCKADDR *) &addr, sizeof (addr))) {closesocket (sock); cout << WSAGetLastError (); return 0;} Set the SOCKET to receive all data for all NICs that flow through the bound IP, including packets received and sent u_long Sioarg = 1;dword wt = 0;IF (Socket_error = WSAIoctl (sock, Sio_rcvall, & Sioarg, sizeof (SIOARG), NULL, 0, &AMP;WT, NULL, NULL)) {closesocket (sock); cout << WSAGetLastError (); return 0;} We only need to receive data, so set to block Io, using the simplest IO model u_long bioarg = 0;if (Socket_error = = ioctlsocket (sock, Fionbio, &bioarg)) { Closesocket (sock); cout << WSAGetLastError (); return 0;} Start receiving data//Because the front is already set to block IO,RECV will not be returned until the data is received. CNT = 1;char Buf[65535];int len = 0;do{len = recv (sock, buf, sizeof (BUF), 0), if (Len > 0) {decodeip (buf, Len);}} while ( Len > 0); closesocket (sock); return 0;}

Finally, because this program requires privileged user rights, so we find the EXE under the Debug program, right-click to run with administrator rights.


C + + captures the IP packet of the native network card and resolves its implementation

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.