aa
相关函数原型及参数类型:
函数原型:int inet_aton(const char *cp, struct in_addr *inp); in_addr_t inet_addr(const char *cp); in_addr_t inet_network(const char *cp); char *inet_ntoa(struct in_addr in); struct in_addr inet_makeaddr(int net, int host); in_addr_t inet_lnaof(struct in_addr in); in_addr_t inet_netof(struct in_addr in); int inet_pton(int af, const char *src, void *dst); inet_pton() returns 1 on success (network address was successfully converted). 0 is returned if src does not contain a character string representing a valid network address in the specified address family. If af does not contain a valid address family, -1 is returned and errno is set to EAFNOSUPPORT. 参数类型:/* Internet address. */typedef uint32_t in_addr_t;struct in_addr{ in_addr_t s_addr;};
inet_addr函数:将IPv4的点分十进制地址转换为网络字节序
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> int main(int argc, char *argv[]){ struct in_addr addr; if (argc != 2) { fprintf(stderr, "%s <dotted-address>\n", argv[0]); exit(EXIT_FAILURE); } if (inet_aton(argv[1], &addr) == 0) { perror("inet_aton"); exit(EXIT_FAILURE); } printf("addr = 0x%-10x\n", addr.s_addr); printf("%s\n", inet_ntoa(addr)); exit(EXIT_SUCCESS);} [email protected]:~/tmp/network$ ./a.out 127.0.0.1addr = 0x100007f 127.0.0.1
char *inet_ntoa(struct in_addr in) { static char buf[INET_NTOA_MAX_LEN]; return inet_ntoa_r(in, buf); }
注意:
1、inet_ntoa的返回值是一个static类型的char *指针,所以使用的时候需要注意(不可重入,可以使用线程安全的inet_ntoa_r函数代替)
2、The inet_addr() function converts the Internet host address cp from IPv4 numbers-and-dots notation into binary data in network byte order. If the input is invalid, INADDR_NONE (usually -1) is
returned. Use of this function is problematic(有问题的) because -1 is a valid address (255.255.255.255). Avoid its use in favor of inet_aton(), inet_pton(3), or getaddrinfo(3) which provide a cleaner
way to indicate error return.(因为其返回值为in_addr_t,当返回-1时,有二义性->表示两个含义)
3、inet_aton() returns nonzero if the address is valid, zero if not.
4、inet_aton/inet_addr/inet_ntoa仅适用于ipv4地址
5、inet_pton/inet_ntop对于v4和v6地址均适用
时间: 2024-10-13 11:33:57