WinPcap Network Programming 10 WinPcap combat, two hosts through the intermediate host communication

Source: Internet
Author: User
Tags get ip

Note: This blog is also not aimed at the party, the source code and so on I will not be completely public, this article written out for everyone's network programming or curriculum design to provide certain ideas.

Well, the task we need to accomplish this time is:

Complete two hosts via intermediate host data Communication (Network layer)

    • Increase the forwarding capability based on IP address
    • Add Network layer Encapsulation

In fact, the most important is based on the IP address forwarding function, the network layer of encapsulation in fact, we have done in the primary function.

First, the idea of the experiment is that a sends data through intermediate Host B to C. Then B as a router, B to listen to two network cards, one network card from the data sent through another network card.

As follows:

A--------->b1===b2------------>c

As can be seen from the figure, the B host of two network card data interoperability, A and B1 in a LAN, B2 and C in another LAN.

Like this, now roommate a in the wired internet, My Computer B is also using wired Internet, our wired in the same LAN, my Computer B at the same time scattered a wireless network, my mobile phone C and connected to the wireless.

So to achieve a to C data transfer, that is, to simulate roommate A to send data to my phone C, then the process is this:

Roommate a sends data to my NIC on a wired LAN B1,B1 data is forwarded to the wireless LAN via the network card B2, to my phone C via WLAN.

A send to build a frame, the destination MAC address is B1, the destination IP is c. B is to open two network card, B1 listen to receive data, B2 network card is to use the ARP protocol to scan the IP in the WLAN and Mac,b get to a sent frame, resolve its IP address and MAC address, matching the IP and Mac corresponding table just scanned, the source MAC switch to B2 network card mac , the purpose of Mac change to C Mac,ip unchanged, data is unchanged. The new frame is built and sent out.

Well, that's basically the way it is.

Requires three programs, one is send, one route, one receive. So altogether three programs to run at the same time to execute.

Above is my general idea, if have the mistake, also please correct me. The code is now complete.

The code is not exposed and only provides some key code parsing:

First, the sending side

In fact, the sending side and the primary function of the send almost

The interactive process that is written by the individual is as follows:

IP address: 121.250.216.221   MAC Address: 3c970e4b56d6con:127-------------------------------------------IP Address : 121.250.216.227   MAC Address: 089e01b948f4con:128-------------------------------------------IP Address: 121.250.216.228   MAC Address: 10bf48705aeecon:129 get the MAC address, enter the IP address you want to send: 192.168.1.3 Please enter what you want to send: Im CQC what to send: Im CQC

The specific code no longer resolves, the previous primary function.

Second, the routing side

First, open two network cards, declare two network card objects and processors

pcap_if_t  *d,*d2;//The selected network adapter pcap_t *adhandle,*adhandle2;           The capture instance is the object returned by Pcap_open, Adhandle is used to send data, Adhandle2 is used to receive data

One used to receive a send, defined here Adhandle is used to send, Adhandle2 is used to receive data.

Then open the adapter just in the main method, open two network cards in advance

int num;printf ("Please enter the network card code that you want to forward data: \ n"),//Let the user choose which adapter to forward scanf_s ("%d", &num);//Jump to the selected adapter for (D=alldevs, i=0; i< Num-1; D=d->next, i++);//Run here to explain the user's input is legal, find the Send data nic if ((Adhandle = Pcap_open (d->name,//device name 65535,//store the content length of the packet Pcap_ Openflag_promiscuous,//Promiscuous mode 1000,//timeout time NULL,//Remote Authentication ERRBUF//error buffering) = = null) {//Open adapter failed, print error    Error and Release adapter list fprintf (stderr, "\nunable to open the adapter.%s was not supported by Winpcap\n", d->name);    Release device list Pcap_freealldevs (Alldevs); return-1;} int num2;printf ("Please enter the network card code you want to receive data:"),//Let the user choose which network card to use to receive data scanf_s ("%d", &num2);//The user entered a number beyond the reasonable range//jump to the selected adapter for (d2= Alldevs, i=0; i< num2-1; D2=d2->next, i++);//Run here to indicate that the user's input is valid if ((Adhandle2 = Pcap_open (d2->name,//device name 65535,//content length of the storage packet Pcap_ Openflag_promiscuous,//Promiscuous mode 1000,//timeout time NULL,//Remote Authentication ERRBUF//error buffering) = = null) {//Open adapter failed, print error Error and Release adapter list fprintf (stderr, "\nunable to open the adapter.%s was not supported by Winpcap\n", d2->name);

Next, use the handle processor for sending to scan its LAN IP, get the MAC address of the LAN, record in a table, and store the correspondence between IP and Mac.

This table can be stored in a struct array, for example:

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

So above is the preparation work, we completed the two network card open, send network card scan to get LAN Mac, Next is the most important listening and forwarding.

What about this? Then open a new thread.

Let's declare a new routing thread.

DWORD WINAPI routethread (LPVOID lpparameter);

So what parameters does the thread want to receive?

The first thing you have to do is two network adapter processors, Adhandle and Adhandle2 are already initialized in the main method, and Alldevs can hold this pointer to release the list of devices, releasing resources and exiting when an error occurs.

It's been declared in the primary function.

struct Sparam sp;
struct Gparam GP;

These two are the two parameters that are sent to the ARP thread and the receiving ARP thread, so we'll define a new struct, modeled after this function.

struct rparam{pcap_t *adhandle_rec;pcap_t *adhandle_send;pcap_if_t  * ALLDEVS;       all network adapters};

Initialize the assignment in the Main method

Rp.adhandle_send = Adhandle;rp.adhandle_rec = Adhandle2;rp.alldevs = Alldevs;

Pass this thread as a parameter

Routethread = CreateThread (null, 0, (lpthread_start_routine) routethread, &rp,0, NULL);

The fourth parameter is to pass the structure in. Note that this statement is best not to be directly called in the Main method, which can be turned on after all the MAC addresses have been obtained.

So let's talk about what this thread has done, just a little bit about the core part.

The first time you start this thread will always be executed, then you can join

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

Such a while judgment statement to listen to the packet received, and then parse 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];}    Get IP Data Header Location IP = (Ipheader *) (Pkt_data +14); 14 for Ethernet frame head length//Get TCP header position Ip_len = (Ip->version_hlen & 0xf) *4;tcp = (Tcpheader *) ((U_char *) ip+ip_len);d ata = (cha R *) ((U_char *) tcp+20);p rintf ("data:%s\n", data);p rintf ("IP:");p rintf ("%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]);p rintf ("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]);


Then each received a data, the construction of a new frame forwarding out, the purpose of the Mac first match the list table, if the list is not found, then I asked him to specify a Mac, such as broadcast Mac. The source MAC address assigns the MAC address of the NIC.

Note that the data length in the traditional Ethernet is 45-1500, then I build the parsed data before the build, because I have declared the Sendbuffer as a fixed length, in order to prevent the crossing, I first make a length judgment.

The following starts the build frame Send//First judge data max value less than 1500if (strlen (data) <1500) {//Purpose 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]; Assignment 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];//Assignment source MAC address memcpy (send_ethernet. Sourmac, Send_hostmac, 6); send_ethernet. Ethtype = htons (0x0800);//Assignment sendbuffermemcpy (&sendbuffer, &send_ethernet, sizeof (struct ethernetheader));

The above is only assigned to the frame head, as for the IP header, TCP header, the assignment of data on the reference to the primary function to assign values, do not forget the checksum test. Well, basically, that's the way the packet is received and forwarded out.

Third, receive

Do not change, is the primary function of the reception, write a small optimization measures, to prevent the receipt of excessive data frame and caused by constant jumping, resulting in you do not see the received things.

It's good to add a filter when printing. Some of the code is as follows:

Prompts the user to enter the IP address to receive in the Main method

printf ("Please enter the IP address to receive, enter 0.0.0.0 for all receive, please 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, IP input is not valid, please re-enter: \ n");} Else{legal = True;}}

The judgment when printing

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]);p rintf ("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]);p rintf ("%s\n", data);p rintf ("-----------------------------------------------------\ n");}


Good, the code first broadcast so much, concrete implementation as long as there are ideas I believe certainly not difficult, if there is a problem, welcome to communicate with me.

My e-mail [email protected]




WinPcap Network Programming 10 WinPcap combat, two hosts through the intermediate host communication

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.