struct in_addr 結構體:小程序
struct in_addr {網絡
in_addr_t s_addr;函數
};spa
表示一個32位的IPv4地址。code
in_addr_t通常爲32位的unsigned int,其字節順序爲網絡字節序,即該無符號數採用大端字節序。其中每8位表示一個IP地址中的一個數值。blog
打印的時候能夠調用inet_ntoa()函數將其轉換爲char*類型。ip
頭文件爲:#include <arpa/inet.h>內存
inet——ntoa()函數用於將一個十進制網絡字節序轉換爲點分十進制IP格式的字符串。字符串
函數原型爲:char*inet_ntoa(struct
in_addr in);
原型
頭文件爲:
arpa/inet.h
網絡字節序和主機字節序比較容易混亂(大端表示和小端表示)。
網絡字節序採用大端表示,就是數據的高位要存放到低地址。
而大多數主機字節序採用小端表示(也有采用大端表示的主機字節序),就是數據的低位放到低地址。
好比無符號整型1338378,的二進制表示爲:
數據的高位----------------------------》數據的地位
00000000 00010100 01101100 00001010
因此採用小端表示的主機字節序時,內存中存放的形式爲:
低地址----------------------------------------》高地址
00001010 01101100 00010100 00000000
因此能夠本身寫個小程序來代替inet_ntoa()函數。
#include<stdio.h> #include<stdlib.h> #include<string.h> void toStringIP(const unsigned int ip,char *stringIP); int main() { unsigned int ip=1338378; char* stringIP = (char*)malloc(16); memset(stringIP,0,16+1); toStringIP(ip,stringIP); puts(stringIP); return 0; } void toStringIP(const unsigned int ip,char *stringIP) { unsigned int tempIP=ip; for(int i=0;i<3;i++) { unsigned char part=(char)tempIP; char temp[4]; sprintf(temp,"%d.",part); strcat(stringIP,temp); tempIP=tempIP>>8; } unsigned char part=(char)tempIP; char temp[4]; sprintf(temp,"%d",part); strcat(stringIP,temp); }
若是您以爲對您有幫助,請點贊哦^^