|
Q & A on Data Typing IP Addresses Q: I thought I was quite clear about the byte order issue during my 636 class, but when I revisit it now, I found I am somewhat confused about the dealing with IPaddress. In our 636 project, we never convert the IPaddr between the network order and host order. But, it is defined as unsigned long. I thought I understood it because I thought that is because we never really view the address as some long value, so, it is basically like an array of 4 bytes(in which case, the order does not matter), but in our ip.h, those macros like IP_CLASSA(x), they actually are taking the value of the IP address fields. So, are those macros machine-dependent? If they are, why not we apply ntohl on the IP address fields just like all the other fields longer than one byte? A: IP addresses are stored in successive octets in the order in which they are written in dotted decimal. Thus, 128.10.2.3 is stored with 128 in the first octet, 10 in the next, and so on. There is no ``conversion'' from local to network byte order because the same order is used on all computers. In the original version of the TCP/IP stack I wrote, IP address fields were, indeed, declared to be an array of four unsigned characters. However, treating each address as an array resulted in inefficient code -- it required a loop to compare two addresses. To improve code speed, we changed the declarations in later versions to 32-bit integers. As a result, an entire address can be copied, compared to another address, or masked in a single machine instruction. So, although the addresses are declared to be integers, the code never performs operations such as addition or subtraction. Q: Also, I was debating the following issue with a friend. Let's say we have a 32-bit machine which will store the MSB in the highest address( I could not remember it is big endian or little endian). A: Little endian. Q: If 4 bytes with value 1,2,3,4 arrived from a network interface card with that order, will the machine store them in the memory( some buffer) as 1 2 3 4 or 4 3 2 1 ( the right most positon has highest address) I am having the opinion of the former, my friend holds the latter, who is correct? A: Most DMA devices do not change byte order -- they merely store incoming bytes in successive locations of memory. Suppose the Network Interface Card is programmed to read the next packet into location 5000 in memory. The card places the first byte in 5000, the next in 5001, the next in 5002, and so on. If the packet contains an integer in network standard byte order (big endian) and the computer is little endian, software must perform the conversion after the NIC delivers the packet. |