标签:
《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 #include <stdlib.h> 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 上编译运行的结果为:
在NetBSD-1.0上使用ioctl获取接口配置清单的例子
标签:
原文地址:http://www.cnblogs.com/StupidTortoise/p/4251283.html