Winpcap network programming 10-Winpcap practice, two hosts communicate through the intermediate host, winpcap Network Programming

Source: Internet
Author: User

Winpcap network programming 10-Winpcap practice, two hosts communicate through the intermediate host, winpcap Network Programming

Note: I will not make this blog completely public if I reach out to the party, the source code, and so on. This article provides some ideas for network programming or curriculum design ..

Okay. The task we need to complete this time is:

Completes data communication between two hosts through the intermediate host (Network Layer)

  • Added the IP address-based forwarding function.
  • Added Network Layer Encapsulation

In fact, the most important thing is the IP address-based forwarding function. We have done a good job in the encapsulation of the network layer.

First, the idea of the experiment is that A sends data to C through the intermediate host B. Then B acts as a router, and B needs to listen to two NICs. data sent from one Nic is sent from the other Nic.

As follows:

A ---------> B1 === B2 ------------> C

From the figure, we can see that the two NICs of host B are interconnected, while A and B1 are in one LAN, while B2 and C are in another LAN.

For example, now roommate A is using wired Internet access, and my computer B is also using wired Internet access. Our wired network is in the same LAN, and my computer B has A wireless network at the same time, my mobile phone C is connected to this wireless device again.

The process is as follows:

Roommate A sends data to my Nic B1 in the wired LAN, B1 forwards the data to the NIC B2, and reaches my mobile phone C through the LAN.

A creates A frame for sending. The destination MAC address is B1 and the destination IP address is C. B needs to enable two NICs, B1 listens to receive data, B2 Nic uses ARP to scan the IP address and MAC address in the wireless LAN, B gets the frame sent by, resolve its IP address and MAC address, match the list of IP addresses and MAC addresses that have just been scanned, change the source MAC address to the B2 Nic MAC address, and change the target MAC address to the c mac address. The IP address remains unchanged, data remains unchanged. Create a new frame and send it out.

Okay, that's the general idea.

Three programs are required. One is sending, the other is routing, and the other is receiving. So a total of three programs should be run at the same time.

The above is my general idea. please correct me if you have any mistakes. Code implementation is now complete.

The code is not publicly available for the moment. Only some key code parsing is provided:

I. Sender

In fact, the sending end is similar to that of the basic function.

The interaction process written by the individual is as follows:

IP Address: 121.250.216.221 MAC address: large address: 121.250.216.227 MAC address: 089e01b948f4con: large address: 121.250.216.228 MAC address: 10bf48705aeecon: 129, enter the IP address of the recipient you want to send: 192.168.1.3 enter the content you want to send: im cqc

The specific code will not be parsed. It is the same as the preliminary function in the previous article.

Ii. Routing end

First, you must enable two NICs and declare the two NICs and the processor.

Pcap_if_t * d, * d2; // The selected network adapter pcap_t * adhandle, * adhandle2; // capture the instance, which is the object returned by pcap_open and used to send data, adhandle2 is used to receive data.

One is used to receive one for sending. Here adhandle is defined to be used for sending, and adhandle2 is used to receive data.

Enable the adapter in the main method. enable two NICs in advance.

Int num; printf ("Enter the NIC code you want to forward data to: \ n"); // You can select an adapter to forward scanf_s ("% d ", & num); // jump to the selected adapter for (d = alldevs, I = 0; I <num-1; d = d-> next, I ++ ); // when running this command, the user input is valid. Find the data transmission network card if (adhandle = pcap_open (d-> name, // device name 65535, // Content Length of the data packet to be stored PCAP_OPENFLAG_PROMISCUOUS, // mixed mode 1000, // time-out NULL, // Remote Authentication errbuf // Error Buffer) = NULL) {// failed to open the adapter. Print the error and release the adapter list fprintf (stderr, "\ nUnable to open the adapter. % s is not supported by WinPcap \ n ", d-> name); // release the device list pcap_freealldevs (alldevs); return-1;} int num2; printf ("Enter the NIC code you want to receive data:"); // Let the user select which Nic to use to receive data scanf_s ("% d", & num2 ); // The number entered by the user exceeds the reasonable range // jump to the selected adapter for (d2 = alldevs, I = 0; I <num2-1; d2 = d2-> next, I ++); // if your input is valid (adhandle2 = pcap_open (d2-> name, // device name 65535, // Content Length of the data packet to be stored PCAP_OPENFLAG_PROMISCUOUS, // mixed mode 1000, // time-out NULL, // Remote Authentication errbuf // Error Buffer) = NULL) {// failed to open the adapter. Print the error and release the adapter list fprintf (stderr, "\ nUnable to open the adapter. % s is not supported by WinPcap \ n ", d2-> name );

Next, we use the handle processor for sending to scan its lan ip address, obtain the MAC address in the LAN, record it in a table, and store the correspondence between the IP address and MAC address.

This table can be saved using struct arrays, for example:

struct ip_mac_list{IpAddress ip;unsigned char mac[6];};
Ip_mac_list list [256]; // table for storing IP addresses and MAC addresses

The above is the preparation work. We have enabled two NICs and sent Nic scanning to obtain lan mac. Next, we will add the most important listener and forwarding.

So what should we do? Open a new thread.

Let's declare a new routing thread.

 

DWORD WINAPI RouteThread(LPVOID lpParameter);

What parameters should the thread receive?

The first thing we need is two NICs processors. In the main method, we have initialized adhandle and adhandle2, and alldevs. We can hold this pointer to release the device list, when an error occurs, release the resource and exit.

The primary function has been declared

Struct sparam sp;
Struct gparam gp;

These two parameters are the two parameters in the ARP sending thread and the ARP receiving thread. We define a new struct following this function.

Struct rparam {pcap_t * adhandle_rec; pcap_t * adhandle_send; pcap_if_t * alldevs; // all network adapters };

Initialize the value assignment in the main method.

 

rp.adhandle_send = adhandle;rp.adhandle_rec = adhandle2;rp.alldevs = alldevs;

Input this thread as a parameter

 

routethread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) RouteThread, &rp,0, NULL);

The fourth parameter is to pass the struct. Note that this statement should not be directly called in the main method. You can enable this thread after obtaining all the MAC addresses.

Next, let's talk about what this thread has done. Let's just briefly talk about the core part.

After this thread is enabled, it will be executed all the time, so you can add

while((res = pcap_next_ex(adhandle2,&header,&pkt_data))>=0)

This while judgment statement keeps listening for receiving data packets and then parsing the data.

 

Ethernet = (EthernetHeader *) (pkt_data); for (int I = 0; I <6; I ++) {sou_mac [I] = ethernet-> SourMAC [I];} for (int I = 0; I <6; I ++) {des_mac [I] = ethernet-> DestMAC [I];} // obtain the IP packet header position ip = (IpHeader *) (pkt_data + 14 ); // 14 is the length of the Ethernet frame header // obtain the position of the TCP Header ip_len = (ip-> Version_HLen & 0xf) * 4; tcp = (TcpHeader *) (u_char *) ip + ip_len); data = (char *) (u_char *) tcp + 20); printf ("data: % s \ n", data); printf ("ip: "); printf (" % d. % d. % d. % d-> % d. % d. % d. % d \ n ", ip-> SourceAddr. byte1, ip-> SourceAddr. byte2, ip-> SourceAddr. byte3, ip-> SourceAddr. byte4, ip-> DestinationAddr. byte1, ip-> DestinationAddr. byte2, ip-> DestinationAddr. byte3, ip-> DestinationAddr. byte4); printf ("sou_mac: % 02x-% 02x-% 02x-% 02x-% 02x-% 02x \ n", sou_mac [0], sou_mac [1], sou_mac [2], sou_mac [3], sou_mac [4], sou_mac [5]); printf ("des_mac: % 02x-% 02x-% 02x-% 02x-% 02x-% 02x \ n ", des_mac [0], des_mac [1], des_mac [2], des_mac [3], des_mac [4], des_mac [5]);


Next, each time a data packet is received, a new frame is constructed and forwarded. The target MAC matches the list table first. If the list is not found, I asked him to specify a mac, for example, broadcast MAC. The source MAC address is assigned the MAC address of the NIC.

Note that the data Length in Traditional Ethernet is 45-1500, so I made the parsed data before determining the length and then building it, because I have declared sendbuffer as a fixed length. to prevent cross-border attacks, I first make a length judgment.

// Start frame sending from the following: // first, judge that the maximum data value is smaller than 1500if (strlen (data) <1500) {// The target MACBYTE send_destmac [6]; bool findMac = false; for (int c = 0; c <con; c ++) {if (ip-> DestinationAddr. byte1 = list [c]. ip. byte1 & ip-> DestinationAddr. byte2 = list [c]. ip. byte2 & ip-> DestinationAddr. byte3 = list [c]. ip. byte3 & ip-> DestinationAddr. byte4 = list [c]. ip. byte4) {printf ("Find its MAC! \ N "); findMac = true; send_destmac [0] = list [c]. mac [0]; send_destmac [1] = list [c]. mac [1]; send_destmac [2] = list [c]. mac [2]; send_destmac [3] = list [c]. mac [3]; send_destmac [4] = list [c]. mac [4]; send_destmac [5] = list [c]. mac [5] ;}} if (! FindMac) {send_destmac [0] = 0xff; send_destmac [1] = 0xff; send_destmac [2] = 0xff; send_destmac [3] = 0xff; send_destmac [4] = 0xff; send_destmac [5] = 0xff;} printf ("destmac: % 02x-% 02x-% 02x-% 02x-% 02x-% 02x \ n", send_destmac [0], send_destmac [1], send_destmac [2], send_destmac [3], send_destmac [4], send_destmac [5]); memcpy (send_ethernet.DestMAC, send_destmac, 6 ); // source MAC address BYTE send_hostmac [6]; // source MAC address send_hostmac [0] = local_mac [0]; // assign a value to the local MAC address send_hostmac [1] = local_mac [1]; send_hostmac [2] = local_mac [2]; send_hostmac [3] = local_mac [3]; send_hostmac [4] = local_mac [4]; send_hostmac [5] = local_mac [5]; // assign the source MAC address memcpy (send_ethernet.SourMAC, send_hostmac, 6 ); send_ethernet.EthType = htons (0x0800); // value SendBuffermemcpy (& SendBuffer, & send_ethernet, sizeof (struct EthernetHeader ));

The above only assigned the frame header. As for the IP header and TCP header, the Data assignment should be based on the initial function. Do not forget the checksum check. Okay. In general, this is how data packets are accepted and forwarded.

Iii. Receiving

There is no need to change it, that is, the reception in the primary function. Here, we will write a small optimization measure to prevent too many data frames from being received and causing continuous disorder, So that you cannot see what you receive.

Add a filter when printing. Some code is as follows:

In the main method, prompt the user to enter the IP address to receive

Printf ("Enter the IP address you want to receive. Input 0.0.0.0 indicates all IP addresses are received. Enter \ n"); bool receiveAll = false; u_int ip1, ip2, ip3, ip4; bool legal = false; while (! Legal) {scanf_s ("% d. % d. % d. % d ", & ip1, & ip2, & ip3, & ip4 ); if (ip1 = 0 & ip2 = 0 & ip3 = 0 & ip4 = 0) {receiveAll = true; legal = true; break ;} if (ip1 <0 | ip1> 255 | ip2 <0 | ip2> 255 | ip3 <0 | ip3> 255 | ip4 <1 | ip4> 254) {legal = false; printf ("sorry, the IP address input is invalid. Enter \ n" again) ;}else {legal = true ;}}

Print judgment

if(receiveAll||(ip->SourceAddr.byte1==ip1&&ip->SourceAddr.byte2==ip2&&ip->SourceAddr.byte3==ip3&&ip->SourceAddr.byte4==ip4)){printf("%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d\n",ip->SourceAddr.byte1,ip->SourceAddr.byte2,ip->SourceAddr.byte3,ip->SourceAddr.byte4,    sport,    ip->DestinationAddr.byte1,    ip->DestinationAddr.byte2,    ip->DestinationAddr.byte3,    ip->DestinationAddr.byte4,    dport);    printf("sou_mac:%02x-%02x-%02x-%02x-%02x-%02x\n", sou_mac[0], sou_mac[1], sou_mac[2],    sou_mac[3], sou_mac[4], sou_mac[5]);printf("des_mac:%02x-%02x-%02x-%02x-%02x-%02x\n", des_mac[0], des_mac[1], des_mac[2],    des_mac[3], des_mac[4], des_mac[5]);printf("%s\n",data);printf("-----------------------------------------------------\n");}


Well, the code should be put forward so much. I believe it is not difficult to implement the Code as long as you have ideas. If you have any questions, please contact me.

My mailbox 1016903103@qq.com


Zookeeper
What is winpcap? Can be deleted? Does it affect Internet access?

This cannot be deleted! Local connection! After deletion, you cannot access the Internet!

For WINPCAP

Winpcap (windows packet capture) is the next free and public network access system on windows.
Winpcap is developed to provide win32 applications with the ability to access the bottom layer of the network. It provides the following functions:
1> capture original data packets, including data packets sent/received and exchanged between hosts on the shared network;
2> filter out some special data packets according to custom rules before the data packets are sent to the application;
3> send the original datagram on the network;
4> collect statistics during network communication.
The main function of winpcap is to send and receive raw data packets independently of the host protocol (such as TCP/IP. That is to say, winpcap cannot block, filter or control the sending and receiving of other application datagram. It only listens to the datagram transmitted on the shared network. Therefore, it cannot be used by QoS scheduler or personal firewall. Currently, winpcap is mainly developed for windows NT/2000/XP. This is mainly because only a small part of users who use winpcap use windows 95/98/Me, microsoft has also abandoned win9x development. Therefore, the related program T-ARP is for NT/2000/XP users. In fact, the concept of 9x System in winpcap is very similar to that of the NT system, but there are some differences in some implementations. For example, 9x only supports ANSI encoding, while the NT system advocates Unicode encoding. There is a software called sniffer pro. it can be used as a network management software and has many functions. It can monitor network running conditions, and the data traffic of each machine in the network reflects the IP addresses accessed by each machine and the data flow between them in real time, you can capture packets and set filters to capture only the desired packets, such as POP3 packets, smtp packets, and ftp packets, and find the email user name and password, there are also ftp usernames and passwords. it can also listen on the network where the vswitch is used, but it must be installed with a software on the vswitch. there is also a simple listening software called Passwordsniffer, which can intercept the mailbox user name and password, as well as the ftp user name and password, it can only be used on the HUB network. The famous software tcpdump and ids snort are both written based on libpcap. In addition, the Nmap scanner uses libpcap to capture packets returned by the target host.

WinPcap is a tool used to capture network packets. It can be used to parse network packets on a 32-bit operating platform, including core packet filtering and a underlying dynamic link library, and a high-level system function library, and an application interface that can be used to directly access packets.
Winpcap is a free and public software system. It is used for direct network programming in windows.
Most network applications access the network through a widely used socket. This method is easy to implement network data transmission, because the operating system is responsible for the underlying details (such as the protocol stack and data stream assembly) and provides function interfaces similar to file read/write.
But sometimes, a simple method is not enough. Some applications require an underlying environment to directly manipulate network communication. Therefore, a method to access the network without the support of the protocol stack is required.
Winpcap applies to the following developers:
1. Capture the original data packet. Whether this package is sent to a local machine or an exchange package between other machines.
2. filter data packets by user-defined rules before they are sent to the application.
3. Send raw data packets to the network.
4. Make statistics on network traffic.
These functions depend on device drivers and dynamic link libraries in the Win32 kernel.
Winpcap provides a powerful programming interface, which can be easily transplanted between various operating systems and easily developed by programmers.
What kind of program needs to use Winpcap
Many different tools and software use Winpcap in network analysis, troubleshooting, network security monitoring, and other aspects. Winpcap is particularly applicable to the following full text...>
 

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.