linux 内核printk格式化输出
参考: 如何获得正确的printk格式占位符 — The Linux Kernel documentation
内核printf 系列函数使用 %pISpfc 格式占位符,可以输入 (struct sockaddr_in *) 类型输出人类可读的结果。同时支持ipv4 和 ipv6
例子:
int net_connect_check(struct socket *sock, struct sockaddr *addr)
{
if(IS_ERR_OR_NULL(sock) || IS_ERR_OR_NULL(addr))
return -1;
int allow = 1;
u16 family = sock->sk->sk_family;
unsigned short *snum = 0;
u32 *ipaddress = 0;
int address_match = 0;
struct task_struct *pname = task_group_leader( current );
if ( family == PF_INET || family == PF_INET6 )
{
struct sockaddr_in *addr4 = NULL;
struct sockaddr_in6 *addr6 = NULL;
if ( family == PF_INET )
{
addr4 = (struct sockaddr_in *)addr;
snum = &addr4->sin_port;
ipaddress = (u32 *)&addr4->sin_addr.s_addr;
printk("### v4 sockaddr in => (%pISpfc)\n " , addr4 ); //支持ipv4
address_match = is_match_name(*ipaddress, *snum, task_name(pname));
}
else
{
addr6 = (struct sockaddr_in6 *)addr;
snum = &addr6->sin6_port;
printk("### ipv6 sockaddr in => (%pISpfc)\n" , addr6 ); //同时支持ipv6
address_match = is_match6_name(*ipaddress, *snum, task_name(pname));
}
}
if ( address_match == 1)
{
allow = 0;
}
return allow;
}
以上代码格式化输出结果
### v4 sockaddr in => (192.168.1.1:22) ### v6 sockaddr in => ([::1]:632/0)