在NetBSD-1.0上使用ioctl获取接口配置清单的例子

       《TVP/IP v2》的4.4节介绍了 ioctl 系统调用,所以想验证下实际调用的结果,代码例子如下:

 1 #include <sys/types.h>
 2 #include <sys/socket.h>
 3 #include <net/if.h>
 4 #include <net/if_dl.h>
 5 #include <netinet/in.h>
 6 #include <arpa/inet.h>
 7 #include <sys/ioctl.h>
 8 
 9 
10 int printaddr( const struct sockaddr *sa )
11 {
12     if( sa->sa_family == AF_LINK ) {
13         struct sockaddr_dl *sdl = (struct sockaddr_dl *)sa;
14         int len = sdl->sdl_alen - 1, i;
15         
16         printf("\tAF_LINK\t");
17         for( i = 0; i < len; i++ ) {
18             printf("%02X:", (unsigned char)(sdl->sdl_data)[ sdl->sdl_nlen + i] );
19         }
20         printf( "%02X", (sdl->sdl_data)[ sdl->sdl_nlen + i] );
21     }
22     else if( sa->sa_family == AF_INET ) {
23         struct sockaddr_in *sin = (struct sockaddr_in *)sa;
24         printf("\tAF_INET\t");
25         printf("%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
26     }
27 }
28 
29 int main(void)
30 {
31     struct ifconf ifc;
32     char buffer[200];
33     int len;
34     struct ifreq *ifrp;
35     
36     len = socket(AF_INET, SOCK_STREAM, 0);
37     
38     ifc.ifc_len = sizeof( buffer );
39     ifc.ifc_buf = buffer;
40     if( ioctl(len, SIOCGIFCONF, &ifc) < 0 )
41     {
42         perror("ioctl error");
43         return -1;
44     }
45     
46     len = ifc.ifc_len;
47     ifrp = ifc.ifc_req;
48     for(; len > 0 && ifrp; ) {
49         struct sockaddr *sa = &(ifrp->ifr_addr);
50         printf("%s", ifrp->ifr_name);
51         printaddr( sa );
52         printf("\n");
53         
54         ifrp = (struct ifreq *)((char *)sa + sa->sa_len);
55         len -= sizeof(ifrp->ifr_name) + sa->sa_len;
56     }
57     
58     return 0;
59 }

在  NetBSD-1.0 上编译运行的结果为:

转载于:https://www.cnblogs.com/StupidTortoise/p/4251283.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值