網絡字節序 與 主機字節序
前言
首先需要理解 大端模式
與 小端模式
這兩個點:
這兩種模式代表着數據在內存中是如何存放的,我們直到,一個字節能夠存放8位,如果是超過8位的數據該怎樣存放呢?
如需要存放數據 0x12345678
- 大端模式存放:0x12345678
- 小端模式存放: 0x78563412
不難看出,大端模式也就是高位優先存放,小端模式也就是低位優先存放。
- 大端模式是我們常用的存儲方式,也就是
網絡字節序
(IP地址在網絡中的顯示)。 - 小端模式是主機存儲IP地址的方式,稱爲
主機字節序
。
字節序轉化
下面學習兩類函數:
htons
,ntohs
此類函數主要用於轉換 整型
inet_aton
,inet_addr
,inet_ntoa
.
此類函數主要用於轉換 字符串型
1.主機字節序 ——> 網絡字節序
void test0()
{
int i = htons(0x1234);
cout << i << endl;
printf("%x\n", i);
int j = ntohs(0x1234);
printf("%x\n", j);
int m = htons(111);
cout << m << endl;
int n = ntohs(m);
cout << n << endl;
}
int test1()
{
char ip[] = "192.168.0.101"; //主機字節序, 小端模式
printf("%x\n", inet_addr(ip)); //網絡字節序,大端模式
struct in_addr inaddr;
inet_aton(ip, &inaddr);
printf("%x\n", inaddr.s_addr); //網絡字節序, 大端模式
struct in_addr inaddr2;
inet_pton(AF_INET, ip, &inaddr2);
printf("%x\n", inaddr2.s_addr); //網絡字節序, 大端模式
return 0;
}
2.網絡字節序 ——> 主機字節序
int test2()
{
struct in_addr inaddr;
inaddr.s_addr = 0x6500a8c0;
char ip[16];
printf("%s\n", inet_ntoa(inaddr));
inet_ntop(AF_INET, &inaddr, ip, 16);
cout << ip << endl;
return 0;
}
域名轉換IP地址
如百度轉換爲它的IP地址
int test3()
{
struct hostent *host = gethostbyname("www.baidu.com");
cout << "網站的真正名字:" << endl;
cout << host->h_name << endl;
cout << "地址族 爲IPV4:" << (host->h_addrtype==AF_INET ? "yes":"no") << endl;
cout << "IP地址的字節數爲:" << host->h_length << endl;
cout << "網站的別名有:" << endl;
for (int i = 0; host->h_aliases[i] != NULL; i++)
cout << host->h_aliases[i] << endl;
cout << "網站的IP地址列表:" << endl;
for (int i = 0 ; host->h_addr_list[i] != NULL; i++)
{
char ip[16];
inet_ntop(host->h_addrtype, host->h_addr_list[i], ip, 16);
cout << ip << endl;
}
return 0;
}