文獻參考:
http://roclinux.cn/?p=1160
一、IP地址的表示法:
1、ASCII表示法:
210.25.132.181,也就是字符串形式,英語叫做IPv4 numbers-and-dots notation。
2、整型表示法:
3524887733,整數形式的IP地址,。英語叫做binary data。
二、IP地址的轉換:
IPv4 :
1、inet_addr函數
#include <arpa/inet.h>
in_addr_t inet_addr(const char* strptr);
將字符串轉換爲32位二進制網絡字節序的IPV4地址,即將一個點間隔地址轉換成一個in_addr。
2、inet_ntoa函數
#include <arpa/inet.h>
char* inet_ntoa(struct in_addr in);
3、inet_ntoa函數將一個十進制網絡字節序轉換爲點分十進制IP格式的字符串。
#include <arpa/inet.h>
int inet_aton(const char *string, struct in_addr *addr);
是一個改進的方法來將一個字符串IP地址轉換爲一個32位的網絡序列IP地址。
IPv6 :
1、inet_pton函數
2、inet_ntop函數
程序示例:
#Include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
strcut sockaddr_in src;
src.sin_addr.s_addr = inet_addr("*.*.*.*"); //構建網絡地址。
printf("%s\n",inet_ntoa(src.sin_addr)); //將網絡地址轉換成字符串。
三、本機字節順序與網絡字節順序的轉換
#include <arpa/inet.h>
htons ------"host to network short"
htonl -------"host to network long"
ntohs -------"network to host short"
ntohl -------"network to host long"