Linux 内核 网络地址转换函数 in_aton、 in4_pton 和 in6_pton 定义与使用

Linux内核网络编程经常用到地址转换函数,如字符串转换成网络字节序。这三个函数就提供了相应的功能。

先看一下这三个函数的声明:

#ifndef _LINUX_INET_H
#define _LINUX_INET_H

#include <linux/types.h>

/*
 * These mimic similar macros defined in user-space for inet_ntop(3).
 * See /usr/include/netinet/in.h .
 */
#define INET_ADDRSTRLEN		(16)
#define INET6_ADDRSTRLEN	(48)

extern __be32 in_aton(const char *str);
extern int in4_pton(const char *src, int srclen, u8 *dst, int delim, const char **end);
extern int in6_pton(const char *src, int srclen, u8 *dst, int delim, const char **end);
#endif	/* _LINUX_INET_H */

三个函数头文件都是<linux/inet.h>.,使用是只要包含该头文件就可以了。

in_aton()是将字符串转换成ipv4地址。

addr = in_aton("192.168.1.1");

 

in4_pton()也是将字符串转换成ipv4地址。

参数定义如下:

/**
 * in4_pton - convert an IPv4 address from literal to binary representation
 * @src: the start of the IPv4 address string ,地址字符串
 * @srclen: the length of the string, -1 means strlen(src),字符串长度,可以填写-1
 * @dst: the binary (u8[4] array) representation of the IPv4 address,地址缓存
 * @delim: the delimiter of the IPv4 address in @src, -1 means no delimiter,分隔符
 * @end: A pointer to the end of the parsed string will be placed here,可以填写NULL
 *
 * Return one on success, return zero when any error occurs
 * and @end will point to the end of the parsed string.
 *
 * 成功返回1,出错返回0
 */
int in4_pton(const char *src, int srclen, u8 *dst, int delim, const char **end);

用例:
    __be32 saddr;
    ret = in4_pton("192.168.1.1", strlen("192.168.1.1"), &addr, -1, NULL);

in6_pton()是将字符串转换成ipv6地址。参数和用例如下:

/**
 * in6_pton - convert an IPv6 address from literal to binary representation
 * @src: the start of the IPv6 address string
 * @srclen: the length of the string, -1 means strlen(src)
 * @dst: the binary (u8[16] array) representation of the IPv6 address
 * @delim: the delimiter of the IPv6 address in @src, -1 means no delimiter
 * @end: A pointer to the end of the parsed string will be placed here
 *
 * Return one on success, return zero when any error occurs
 * and @end will point to the end of the parsed string.
 *
 *   成功返回1, 失败返回0
 */
int in6_pton(const char *src, int srclen, u8 *dst, int delim, const char **end);

ipv6地址有三种表达方式:首选格式、压缩格式和映射模式。如下
首选格式: static char ip6_0[] = "aaaa:bbbb:cccc:dddd:0000:1111:2222:3333"; 
压缩格式: static char ip6_1[] = "::1"; 
映射格式: static char ip6_2[] = "::ffff:192.168.1.1"; 

这三种格式都可以传递给in6_pton()函数。

用例:

    static char local_ip[] = "::1"; //地址字符串
    struct in6_addr saddr;   
    ret = in6_pton(local_ip, sizeof(local_ip), (void *)&saddr, -1, NULL);        

参考文档:

1.  inet.h源文件  https://elixir.bootlin.com/linux/v4.3/source/include/linux/inet.h#L54

分享一个很有用的网站,这个网站能够提供搜索Linux 内核函数的定义与实现。当遇到不熟悉的函数时,可以用它来搜索。

https://elixir.bootlin.com/linux/v4.3/source

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章