网络地址转换相关函数使用(inet_addr,inet_ntoa,inet_addr)
转换 函数 相关 网络地址 使用 addr
2023-09-27 14:24:25 时间
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);
}
yinguicai@Cpl-IBP-Product:~/tmp/network$ ./a.out 127.0.0.1
addr = 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地址均适用
相关文章
- C#由转换二进制所引起的思考,了解下?
- Word控件Spire.Doc 转换教程(二十九):在 C# 中将 Word 转换为 PDF 时将单词标题保留为 PDF 书签
- Aspose.Words for .NET使用教程(七):将文档转换为EPUB
- Java利用正则表达式实现中英文日期转换函数封装
- 连续三天说一个事情 : 信号转换
- 利用OpenCV的函数cvtcolor()进行颜色空间转换时需要注意的地方
- clickhouse--json字段类型及基于json相关函数进行行列转换
- MFC中char*,string和CString之间的转换
- Pandas的数据转换函数map、apply、applymap
- iOS十六进制和字符串的相互转换
- sql函数的使用——转换函数
- 有没有一个在线工具可以将Python代码转换为Java代码?
- java时间戳与Date相互转换、日期格式化、给日期加上指定时长、判断两时间点是否为同一天
- C# linq 将数组转换为以逗号或其它符号分隔的字符串
- JQuery判断数组中是否包含某个元素,字母大小写转换函数,判断字符串中是否包含特定字符,
- JS 时间转换函数 字符串时间转换毫秒(互转)
- encoding - 如何将 Dart 的ByteData转换为字符串?
- [MySQL 5.6 ]count 不出来数据,如何通过函数进行转换呢?
- Direct2D教程VI——转换(Transform)
- babel 转换箭头函数
- 练习1-15 重新编写1.2节中的温度转换程序,使用函数实现温度转换计算
- atoi函数--把参数 str 所指向的字符串转换为一个整数(类型为 int 型)
- leetcode算法108.将有序数组转换为二叉搜索树