|
发表于 2005-7-10 22:06:45
|
显示全部楼层
仅仅适用IPv4,代码一定很幼稚,请大家指教啊!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/ioctl.h>
- #include <netinet/in.h>
- #include <net/if.h>
- #include <net/if_arp.h>
- #include <arpa/inet.h>
- #include <errno.h>
- #include <unistd.h>
- #include <net/route.h>
- #include <string.h>
- typedef struct
- {
- char name[16];
- char address[16];
- char netmask[16];
- char broadcast[16];
- char macaddr[18];
- }if_info;
- int read_if_info(if_info* info, size_t* len)
- {
- int fd;
- int numreqs = 6;
- struct ifconf ifc;
- struct ifreq *ifr;
- int n;
- int idx = 0;
- int size;
-
- size = *len;
- fd = socket(AF_INET, SOCK_DGRAM, 0);
- memset(&ifc, 0, sizeof(struct ifconf));
- ifc.ifc_len = sizeof(struct ifreq) * numreqs;
- ifc.ifc_buf = (char*)malloc(ifc.ifc_len);
- do {
- if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
- //perror("SIOCGIFCONF");
- goto err;
- }
- if (ifc.ifc_len == sizeof(struct ifreq) * numreqs) {
- /* assume it overflowed and try again */
- numreqs += 4;
- ifc.ifc_len = sizeof(struct ifreq) * numreqs;
- ifc.ifc_buf = (char*)realloc(ifc.ifc_buf, ifc.ifc_len);
- continue;
- }
- break;
- }while(1);
- ifr = ifc.ifc_req;
- for (n = 0; n < ifc.ifc_len; n += sizeof(struct ifreq)) {
- if (idx >= size){
- goto end;
- }
-
- strcpy(info[idx].name, ifr->ifr_name);
- strcpy(info[idx].address,
- inet_ntoa(((struct sockaddr_in*)&ifr->ifr_addr)->sin_addr));
-
- if (ioctl(fd, SIOCGIFNETMASK, ifr) < 0) {
- goto err;
- }
- strcpy(info[idx].netmask,
- inet_ntoa(((struct sockaddr_in*)&ifr->ifr_netmask)->sin_addr));
-
- if (ioctl(fd, SIOCGIFBRDADDR, ifr) < 0) {
- goto err;
- }
- strcpy(info[idx].broadcast,
- inet_ntoa(((struct sockaddr_in*)&ifr->ifr_broadaddr)->sin_addr));
-
- if (ioctl(fd, SIOCGIFHWADDR, ifr) < 0) {
- goto err;
- }
- sprintf(info[idx].macaddr, "%02X:%02X:%02X:%02X:%02X:%02X",(unsigned char)ifr->ifr_hwaddr.sa_data[0],\
- (unsigned char)ifr->ifr_hwaddr.sa_data[1],(unsigned char)ifr->ifr_hwaddr.sa_data[2],\
- (unsigned char)ifr->ifr_hwaddr.sa_data[3],(unsigned char)ifr->ifr_hwaddr.sa_data[4],\
- (unsigned char)ifr->ifr_hwaddr.sa_data[5]);
- ifr++;
- idx++;
- }
-
- end:
- free(ifc.ifc_buf);
- *len = idx;
- return 0;
- err:
- free(ifc.ifc_buf);
-
- return -1;
-
- }
复制代码 |
|