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 內核函數的定義與實現。當遇到不熟悉的函數時,可以用它來搜索。