ARP implementation principle
Author <asdjf@163.com> 2002/11/01
ARP is the abbreviation of Address Resolution Protocol. In essence, Address Resolution Protocol is used to map network addresses to physical addresses. In terms of concept, it is to find a ing method f so that "physical address = f (Network Address )". There are two basic types of physical addresses: Ethernet and PRONET. network addresses are specific to IP addresses, and the ing method requires high efficiency. Specifically, Ethernet is used to dynamically bind the conversion method. Why is it so troublesome not to use the same address directly? The TCP/IP network was invented to interconnect different types of computers. Its architecture is layered and the layers are independent of each other. Changing the implementation of the physical layer does not affect the network layer.
The ing between 32-bit IP addresses and 48-bit physical IP addresses over Ethernet uses the dynamic binding and conversion method to encounter many details, such as reducing broadcast, ARP packet loss, and changing physical IP addresses (replacing NICS), move (move the device to another subnet), disappear (shut down), and so on. ARP high-speed cache is usually set, and ARP ing tables are processed through learning, aging, updating, and overflow algorithms to solve these problems. In this example, ARP receives any arp/IP packet pointing to the IP address of the current node and extracts the address pair from it. When no corresponding entry exists in the ARP cache, it is added to the ARP receiving part; aging refers to setting the lifetime domain for each item to replace the old address ing item; Updating refers to updating the existing corresponding items in the cache when ARP extracts the new address pair; the overflow algorithm is used to replace the old address pair when the cache is full.
I found several TCP/IP source codes and compared them to their implementations. They are very different and flexible. Some codes do not implement ARP cache. Only a few global variables are used to record the source IP address and source MAC address. Before each communication, the global variables are directly operated, point-to-point communication is an effective solution, while some code is huge and complicated, and detailed processing is refined. For example, ARP high-speed caching, multi-address nodes, and network management support for viewing/dynamic ARP-related parameters, re-sending, and IPv6 support are implemented. My opinion is: the essence of ARP is address translation. As long as we grasp this soul, we can grasp the General Direction of design. The specific implementation process has its own characteristics and varies from person to person. There is no uniform requirement, and some functions can not be implemented. Some advantages cannot be both done, but the only thing that remains unchanged is the idea.
Based on several existing IP protocol stacks and the features of 51 single-chip microcomputer, I have implemented my own ucos51-Based TCP/IP protocol stack solution. It is just a specific implementation example. Different people have different design methods. I ensure that my solution can be used normally and has good completeness.
------------------------------
| Status | TTL | IP address | MAC address | Learning
------------------------------
| 0 | FF | X: X | XXXX | <--- aging
------------------------------
| 0 | FF | X: X | XXXX | update
------------------------------
Figure 1 ARP cache table full processing
As shown in figure 1, the ARP cache table consists of four fields: Status, lifetime, IP address, and MAC address. The Status field indicates whether the address pair is valid (0-idle 1-occupied). The lifetime field is used for aging operations. It is initially saved to the maximum value, which will be called by the OS time function later, minus 1 per second, the IP address and MAC address fields keep the ing between the network address and physical address. Here, there is no design of the first pointer and record fields of the send data linked list. I handed the resend operation to the upper-layer software for unified processing, which is a special feature of this program. Four operations are completed around the ARP cache table: learning, aging, updating, and full table processing. For details, see the pseudo-code list. You can use the OS shell command ls to view the content of the ARP table, but it does not support modification. This function is useful for testing. (Example 2 of the displayed content)
% Ls
ARP table:
Status ttl ip address MAC address
========================================================== ==========
01 78 172.18.92.86 0050babd4c7e
%
Figure 2 Examples of content displayed in the ARP cache table
Table full processing
|
V arp request
--------- ----------- ---------->
| Learning/update | <-----
Aging ---> | ARP table | <------------ | ARP processing |
|--->
--------- ----------- <----------
^ ARP response
| Learning/updating
---------
|
| Ip_in |
|
---------
Figure 3 ARP Processing
0 8 16 24 31
---------------------------------------------------------------------
| Hardware type | protocol type |
---------------------------------------------------------------------
| Hardware address length (hlen) | protocol length (Plen) | operation |
---------------------------------------------------------------------
| Sender header (eight-bit group 0-3) |
---------------------------------------------------------------------
| Sender's header (eight-bit Group 4-5) | sender's IP address (eight-bit group 0-1) |
---------------------------------------------------------------------
| Sender IP address (eight-bit Group 2-3) | destination header (eight-bit group 0-1) |
---------------------------------------------------------------------
| Target header (eight-digit Group 2-5) |
---------------------------------------------------------------------
| Target IP address (eight-bit group 0-3) |
---------------------------------------------------------------------
Figure 4 ARP packet structure
3. I mainly use five functions to implement the entire ARP processing process. ARP initialization (arp_init), ARP request (arp_request), ARP response (arp_answer), ARP response processing (arp_process), and ippacket receiving preprocessing (ip_in ). After implementing the NIC driver, all ARP processing operations are to fill in the ARP packet (the ARP packet structure is shown in Figure 4). For details, see the pseudo-code list.
Arp_init initializes the ARP table. In summary, the ARP table state field is cleared by 0.
Arp_request completes ARP request operations. The ARP Protocol requires the program to determine whether the IP address belongs to the same subnet Based on the subnet mask. If the IP address is in the same subnet, the program requests the target MAC address; otherwise, the program requests the default gateway MAC address.
Arp_answer is relatively simple. You only need to exchange the ARP request packet address and enter your MAC address and few changes before sending it.
Arp_process processes the ARP response. It mainly learns and updates ARP tables.
Ip_in is used to extract address ing information to actively learn and update IP packets in a timely manner. My program will not take the initiative to learn the MAC address information not sent to its own IP address, because the ARP table has limited capacity in 51, and only frequently used address pairs should be stored in it, otherwise, the ARP table will become invalid once "bumps" occur.
Some ARP implementation schemes adopt the data-driven mode, and the parameters can be configured. A unified program is used to load different configuration data and perform different operations. In this way, the program version is unified. Different applications only need to load different configuration data without changing the program, which is conducive to later maintenance. However, considering 51 resource shortage and Security, my solution only shows that ARP tables cannot be modified. Users can use their imagination to add new features here. In addition, the ARP program should remember the last request to avoid re-sending. However, considering resource shortage, it is also free. In fact, it doesn't matter. resend it. Table full processing uses a Lossy acceleration algorithm, which is fast and effective. In addition, this program cannot be directly used for Embedded Gateway products.
The ucos51 operating system provides a good memory management function. I used it to set three buffers for storing different types of data packets. The memory is applied before use and released after use to effectively use the resources.
System features: 1. preemptible priority; 2. Message-driven; 3. Serial Server mode.
System advantages: 1. No CPU resources are consumed during waiting; 2. Timeout protection, no deadlock; 3. clear and easy-to-understand ideas.
The system uses int0 as the NIC interrupt input port based on the interrupt driver. ISR registers only use four bits: OVW overflow error/txe sending interrupted error/PTX sending success/PRx receiving success. The TCP/IP protocol stack is used as a task to break away from the kernel. The overall framework is shown in 5, 6, and 7. For the main program framework, see the pseudocode list (rxsem and txsem are initialized to 0)
----------
| Nic interruption |
----------
|
V
---------- |>
| Sending semaphores | receiving completion/receiving overflow error
| Sempost | ----> -------------- rxsempost
---------- |>
| An error occurred while sending/sending interrupted
----------> -------------- Txsempost
Figure 5 Nic interrupt handling program
Enter
| ------
V | send
---------- | Low priority
------> | Waiting | <---
| Txqpend | <--------------------------
| ---------- |
| Txqfifo is not empty |
| V | --- <---
| ---------- | Data source | data sent by each task
| Sending package |
| ---------- | -----
| Txqfifo
| V |
| ------------------- |
| Releases memory |
| (The package has been saved to the ram of the NIC) |
| ------------------- |
| ----- |
| V |
| ----------- |
| Waiting | <-- | (equivalent to discarding the sending package)
| Txsempend | <----------- |
| ----------- |
| Sent/timed out |
| V |
| Y ---------------- ----------- |
-<--- | Is the message sent successfully? | Resend the nth time |
| (No error and no timeout) | n <n |
---------------- ----------- |
| N/^/|
V n |
------------------> ------ |
| Has it been sent n times? | ----------> --------
--------------- Y
Figure 6 sending Flowchart
Enter
| -----
V | accept
----------- | High priority
------------------> | Waiting | <--
| ---------> | Rxsempend | <---------------
| -----------/| // |/
| Received package or |
| V receiving error or |
| Timeout |
| ----------- | ----------
| Save and clear ISR | reset the NIC |
----------- | ----------
| Rxsempost |/^ // ^/
----------- | V |
| ------------------ |
| Timeout and no new package and no error | Y |
| (Deadlock Prevention) |->-|
| ------------------ |
/| (Not executed | n |
| Rxsempost) v |
| ------------ Y |
| Receiving overflow error | ---> --------- |
| ISR-OVW |
| Y | n ------------ |
------------------ | N |
| Is there any package in the Nic? | V |
| Curr! = Bnry + 1 | ------------------------ y |
------------------ | Read the header and check whether there is a logical error. | ---> -------
| ------------------------
/| N
| V
| ------------------------
---------- | Apply for proper capacity based on the package length |
| Releases memory | small memory and stores it in the entire package |
---------- |, Adjust bnry |
/^ // ^ /------------------------
|
| V
| N ----------------------------
| --- <--- | Is it a packet sent to your own IP address? |
| ----------------------------
| Y
| V
| ------------
| Package distribution |
| ------------
|
| V
| ----------------------------
|
| V -------------------------- ip_in Filter
| V v
| Arp icmp (PING) UDP TCP
|
| ----------------------------
| Serial Processing
| (32bitmcu can be designed as a concurrency Mode)
| --------- <-------------
Figure 7 receiving Flowchart
I checked it several times and it seems that it is complete. It works normally in various situations. In the case of overload traffic, only packets are thrown and no crash occurs. Of course, due to my limited access to information and my personal limitations, there must be errors and omissions. I hope you will give your comments and suggestions.
Pseudocode list:
Arp_init () // ARP cache Initialization
{
For (I = 0; I <arptabsize; I ++)
Arptable [I]. Status = 0;
}
Arp_request (destination IP address) // ARP request
{
// Determine whether the IP address belongs to the same subnet and submit the task to the upper-layer software for processing.
// (It determines whether to request the nic ip address or the default gateway IP address ),
// This helps reduce the amount of code.
// Apply for a small memory
Parp = osmemget ();
// Enter the Ethernet frame
Ethernet protocol = 0x0806; // ARP Protocol
Target MAC address = 0 xFFFF; // broadcast address
Source MAC address = Your MAC address;
// Enter the ARP table
Hardware type = 0x0001;
Protocol type = 0x0800;
Hardware address length = 0x06;
Protocol length = 0x04;
Operation = 0x0001; // request
Sender header = MAC address of the sender;
Sender IP address = source IP address;
Target header = 0x0000;
Destination IP address = destination IP address;
// Fill pad
NO content is filled with 0;
// Send the ARP packet to the txqfifo Cache
Osqsend (qid, * PARP );
}
Arp_answer (* PARP) // ARP response
{
Learn/update the ARP cache table;
// Modify the received ARP packet to form an ARP response
// Enter the Ethernet frame
Target MAC address = source MAC address sent from the peer (NIC/gateway;
Source MAC address = Your MAC address;
// Enter the ARP table
Target header = sender header; Sender header = MAC address of the sender;
Exchange the sender's IP address and target IP address;
Operation = 0x0002; // ARP response
// Send the ARP packet to the txqfifo Cache
Osqsend (qid, * PARP );
}
Arp_process (* PARP) // ARP response Processing
{
// Update
For (I = 0; I <arptabsize; I ++ ){
If (arptab [I]. Status = 1 ){
If (arptab [I]. ipadr = source IP address of the received ARP response packet ){
Arptab [I]. TTL = maximum lifetime;
Arptab [I]. ipadr = source IP address of the received package;
Arptab [I]. macadr = source MAC address of the received package;
Return;
}
}
}
// Learn
For (I = 0; I <arptabsize; I ++ ){
If (arptab [I]. Status = 0 ){
Arptab [I]. Status = 1;
Arptab [I]. TTL = maximum lifetime;
Arptab [I]. ipadr = source IP address of the received package;
Arptab [I]. macadr = source MAC address of the received package;
Return;
}
}
// Fast algorithms with full table processing and lossy Performance
Arptab [Index]. Status = 1; // Note: index is a global variable and stores the ARP cache table index. Add 1 modulo for each processing.
Arptab [Index]. TTL = maximum lifetime;
Index ++;
If (index> = arptabsize) Index = 0;
}
Ip_in (* PIP) // ip packet filtering (ARP Address learning) Note: The IP packet is processed here. The pseudo code is similar to the above program, but the source code is very different.
{
// Update
For (I = 0; I <arptabsize; I ++ ){
If (arptab [I]. Status = 1 ){
If (arptab [I]. ipadr = source IP address of the received IP packet ){
Arptab [I]. TTL = maximum lifetime;
Arptab [I]. ipadr = source IP address of the received package;
Arptab [I]. macadr = source MAC address of the received package;
Return;
}
}
}
// Learn
For (I = 0; I <arptabsize; I ++ ){
If (arptab [I]. Status = 0 ){
Arptab [I]. Status = 1;
Arptab [I]. TTL = maximum lifetime;
Arptab [I]. ipadr = source IP address of the received package;
Arptab [I]. macadr = source MAC address of the received package;
Return;
}
}
// Fast algorithms with full table processing and lossy Performance
Arptab [Index]. Status = 1; // Note: index is a global variable and stores the ARP cache table index. Add 1 modulo for each processing.
Arptab [Index]. TTL = maximum lifetime;
Index ++;
If (index> = arptabsize) Index = 0;
}
Timer () // soft timer task for ARP aging
{
For (;;){
Taskdelay (1 second );
For (I = 0; I <arptabsize; I ++ ){
If (arptab [I]. Status = 1 ){
If (arptab [I]. TTL = 0)
Arptab [I]. Status = 0;
Else
Arptab [I]. TTL --;
}
}
}
Main Program Framework:
Initnic // initialize the NIC
// Create a resource
Txsem and rxsem semaphores
Txqfifo queue
Large, medium, and small memory settings
// Create a task
Accept
Sending
.
.
.
References:
1. The first, second, and third volumes of "using TCP/IP for Internet interconnection" (version 3rd) Douglas E. Comer
2. Www.laogu.com
3. Www. sics. se /~ Adam/LWIP/uip6
Q: I have commented on this article. I have read this article for 477 times.