Get the App
SLTechnology News&Howtos  ›  Servers  › 

Socket address API

Shulou Source: shulou.com Published: 2022-06-02 20:39:37 10月03日 Update

Host endianness and network endianness Background: Accumulators in modern CPUs can be loaded (at least) 4 bytes at a time (on 32-bit machines). The order in which these 4 bytes are arranged in ** memory ** affects the value in which they are loaded into integers by the accumulator. Fact: byte order is divided into big-endian and little-endian. 1.1 big endian: An integer whose high byte (23-31 bits) is stored at the low address of memory and whose low byte (0-7 bits) is stored at the high address of memory. 1.2 little endian: The high byte of an integer is stored at the high address of memory, while the low byte is stored at the low address of memory. void byteorder(){ union{ short value; char union_bytes [sizeof( short )]; } test; test.value = 0x0102; if( (test.union_bytes[0] == 1)&&(test.union_bytes[1] == 2)){ printf("big endian"); }else if( (test.union_bytes[0] == 2)&&(test.union_bytes[1] == 1)){ printf("ittle "); }else{ printf("unknown");} 1.3 Modern PCs mostly use small endian, so small endian is also called host endian. 2. When formatted data (32bit or 16bit) Problem 2.1 Solution: The sender always converts the data to big endian. The receiver knows that the data is always big endian, so the receiver can decide whether to convert it according to its own situation.(Small segment conversion, big endian not converted) 3. Big endian is also known as network endian 4. Process byte problem: two processes on the same machine, one is C language, the other is JAVA language, also consider byte order problem (JAVA virtual machine commonly uses big endian) 5.linux conversion big endian function (4) 5.1 unsigned long int htonl (unsigned long int hostlong);5.2 unsigned short int htons (unsigned short int hostshort);5.3 unsigned long int ntohl (unsigned long int netlong);5.4 unsigned short int ntohs(unsigned short int netshort);5.5 The above four meanings are relatively clear: htonl means host to network long, that is, converting long integer (32bit) host byte order into network byte order data. 5.6 Long integer functions are commonly used to convert IP addresses, short integer functions are commonly used to convert port numbers (not limited to this, all formatted data transmitted over the network, these functions should be used to convert byte order)

Tags: Byte big end address memory data host integer network function problem storage low order machine format accumulator language process high order load different Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker OPPO Reno Apple macOS MySQL