具體參見點選打開連結(https://github.com/uttp/UNIX-Network-Programming/tree/master/chapter3)裡面的3.4~3.6
3.4 位元組排序函數
小端和大端
小端:将低序位元組存儲在起始位置
大端:将高序位元組存儲在起始位置
為了測試本機是小端還是大端寫了簡單的程式testByteOrder.cpp具體見本檔案夾
經過測試本機屬于小端
我們還需關注如何在主機位元組序和網絡位元組序之間的互相轉換,這兩種位元組序之間的互相轉化可以使用如下4個函數。
#include <netinet/in.h>
uint16_t htons(uint16_t host16bitvalue);
uint32_t htonl(uint32_t host32bitvalue);
uint16_t ntohs(uint16_t net16bitvalue);
uint32_t ntohs(uint32_t net32bitvalue);
在這些函數名總n代表網絡,h代表主機
3.5位元組操縱函數
#include <string.h>
void bzero(void *dest, size_t nbytes); //把指定的位元組數設定為0
void bcopy(const void *src, void *dest, size_t nbytes);
int bcmp(const void *prt1, const void *ptr2, size_t nbytes);
ANSI C函數
#include<string.h>
void *memset(void *dest, int c, size_t len);
void *memcpy(void *dest, const void *src, size_t nbytes);
int memcmp(const void *ptr1, const void *ptr2,size_t nbytes);
3.6 inet_aton inet_addr 和inet_ntoa函數
這兩組位址轉換函數。他們是ASCII字元串與網絡位元組序的二進制值之間轉換網際位址
(1)inet_aton inet_addr inet_ntoa 在點分是進制數串與它長度為32位的網絡位元組序二進制值間轉換IPv4位址。
(2)兩個比較新的函數inet_pton和inet_ntop對于IPv4和IPv6都合适。
#include <arpa/inet.h>
int inet_aton(const char *strptr,struct in_addr *addrptr);
inet_aton将strptr所指的c字元串轉換成一個32位的網絡位元組序的二進制值,并通過addrptr來存儲。如果成功則傳回1否則傳回0
in_addr_t inet_addr(const char *strptr);
char *inet_ntoa(struct in_addr inaddr);