如題,本篇文章是爲了測試IP地址轉換函數 inet_aton 的實現過程,以及對二進制,八進制和十六進制 C++ 輸出的測試,Ubuntu系統下,可通過 cat /usr/include/arpa/inet.h | grep inet_aton 查找原函數聲明
下面提供測試程序及其結果:
#include <iostream>
#include <arpa/inet.h> // 網絡編程中 包含 inet_aton函數,將點分十進制數串轉換爲32位網絡字節序二進制值
#include <netinet/in.h> // 包含結構定義 struct in_addr{in_addr_t s_addr;}; 其中in_addr_t 爲32位無符號整數 uint32_t
#include <iomanip> // hex 十六進制,oct 八進制 dec 十進制
#include <bitset>
using std::cout;
using std::endl;
using std::hex; // 16,10,8
using std::dec;
using std::oct;
using std::bitset;
int main(int argc, char ** argv)
{
char str[] = "192.168.229.200";
struct in_addr test;
cout<<"the IP str:"<<str<<endl;
int r = inet_aton(str,&test);
cout<<"the IP network byte binary value:"<<bitset<32>(test.s_addr)<<endl;
cout<<"the IP network byte dec value:"<<test.s_addr<<endl;
cout<<"the IP network byte hex value:"<<hex<<test.s_addr<<endl;
cout<<"the IP network byte oct value:"<<oct<<test.s_addr<<endl;
return 0;
}
結果:
the IP str:192.168.229.200
the IP network byte binary value:11001000111001011010100011000000
the IP network byte dec value:3370494144
the IP network byte hex value:c8e5a8c0
the IP network byte oct value:31071324300