Unix Sockets 简明教程
Unix Socket - IP Address Functions
Unix 提供了各种函数调用,可以帮助你处理 IP 地址。这些函数在 ASCII 字符串(人类更喜欢使用)和网络字节序二进制值(存储在套接字地址结构中的值)之间转换互联网地址。
Unix provides various function calls to help you manipulate IP addresses. These functions convert Internet addresses between ASCII strings (what humans prefer to use) and network byte ordered binary values (values that are stored in socket address structures).
以下三个函数调用用于 IPv4 寻址:
The following three function calls are used for IPv4 addressing −
-
int inet_aton(const char *strptr, struct in_addr *addrptr)
-
in_addr_t inet_addr(const char *strptr)
-
char *inet_ntoa(struct in_addr inaddr)
int inet_aton(const char *strptr, struct in_addr *addrptr)
此函数调用将互联网标准点分十进制表示法中的指定字符串转换为网络地址,并将地址存储在所提供的结构中。转换后的地址将采用网络字节序(从左到右排序字节)。如果字符串有效则返回 1,如果出错则返回 0。
This function call converts the specified string in the Internet standard dot notation to a network address, and stores the address in the structure provided. The converted address will be in Network Byte Order (bytes ordered from left to right). It returns 1 if the string was valid and 0 on error.
以下是在使用示例:
Following is the usage example −
#include <arpa/inet.h>
(...)
int retval;
struct in_addr addrptr
memset(&addrptr, '\0', sizeof(addrptr));
retval = inet_aton("68.178.157.132", &addrptr);
(...)
in_addr_t inet_addr(const char *strptr)
此函数调用将互联网标准点分十进制表示法中的指定字符串转换为适合用作互联网地址的整数值。转换后的地址将采用网络字节序(从左到右排序字节)。它返回一个 32 位二进制网络字节序 IPv4 地址,如果出错,则返回 INADDR_NONE。
This function call converts the specified string in the Internet standard dot notation to an integer value suitable for use as an Internet address. The converted address will be in Network Byte Order (bytes ordered from left to right). It returns a 32-bit binary network byte ordered IPv4 address and INADDR_NONE on error.
以下是在使用示例:
Following is the usage example −
#include <arpa/inet.h>
(...)
struct sockaddr_in dest;
memset(&dest, '\0', sizeof(dest));
dest.sin_addr.s_addr = inet_addr("68.178.157.132");
(...)
char *inet_ntoa(struct in_addr inaddr)
此函数调用将指定的互联网主机地址转换为互联网标准点分十进制表示法的字符串。
This function call converts the specified Internet host address to a string in the Internet standard dot notation.
以下是在使用示例:
Following is the usage example −
#include <arpa/inet.h>
(...)
char *ip;
ip = inet_ntoa(dest.sin_addr);
printf("IP Address is: %s\n",ip);
(...)