请问各位高手,在linux下,得到ifconfig输出中的所有IP地址,用C/C++编程。
已知:
gethost and gethostbyname,测试只能得到一个IP地址。
---------------------------------------------------------------
原文:http://www.chinaunix.net/jh/23/161236.html
---------------------------------------------------------------
整理后的代码(在red hat linux 9.0下测试通过):
#include
1<stdio.h>
2#include <sys types.h="">
3#include <sys param.h="">
4
5#include <sys ioctl.h="">
6#include <sys socket.h="">
7#include <net if.h="">
8#include <netinet in.h="">
9#include <net if_arp.h="">
10#include <arpa inet.h="">
11#include <unistd.h> //for close()
12
13#define MAXINTERFACES 16
14
15int main(int argc, char** argv)
16{
17int fd, intrface, retn = 0;
18struct ifreq buf[MAXINTERFACES];
19struct arpreq arp;
20struct ifconf ifc;
21
22if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0)
23{
24ifc.ifc_len = sizeof(buf);
25ifc.ifc_buf = (caddr_t) buf;
26if (!ioctl(fd, SIOCGIFCONF, (char *) &ifc))
27{
28intrface = ifc.ifc_len / sizeof(struct ifreq);
29printf("interface num is intrface=%d\n\n\n", intrface);
30while (intrface-- > 0)
31{
32printf("net device %s\n", buf[intrface].ifr_name);
33/*Jugde whether the net card status is promisc */
34if (!(ioctl(fd, SIOCGIFFLAGS, (char *) &buf[intrface])))
35{
36if (buf[intrface].ifr_flags & IFF_PROMISC)
37{
38puts("the interface is PROMISC");
39retn++;
40}
41}
42else
43{
44char str[256];
45
46sprintf(str, "cpm: ioctl device %s",
47buf[intrface].ifr_name);
48
49perror(str);
50}
51
52/*Jugde whether the net card status is up */
53if (buf[intrface].ifr_flags & IFF_UP)
54{
55puts("the interface status is UP");
56}
57else
58{
59puts("the interface status is DOWN");
60}
61
62/*Get IP of the net card */
63if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface])))
64{
65puts("IP address is:");
66puts(inet_ntoa(((struct sockaddr_in *)
67(&buf[intrface].ifr_addr))->sin_addr));
68puts("");
69//puts (buf[intrface].ifr_addr.sa_data);
70}
71else
72{
73char str[256];
74
75sprintf(str, "cpm: ioctl device %s",
76buf[intrface].ifr_name);
77
78perror(str);
79}
80
81
82/*Get HW ADDRESS of the net card */
83if (!(ioctl(fd, SIOCGIFHWADDR, (char *) &buf[intrface])))
84{
85puts("HW address is:");
86
87printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
88(unsigned char) buf[intrface].ifr_hwaddr.sa_data[0],
89(unsigned char) buf[intrface].ifr_hwaddr.sa_data[1],
90(unsigned char) buf[intrface].ifr_hwaddr.sa_data[2],
91(unsigned char) buf[intrface].ifr_hwaddr.sa_data[3],
92(unsigned char) buf[intrface].ifr_hwaddr.sa_data[4],
93(unsigned char) buf[intrface].ifr_hwaddr.sa_data[5]);
94puts("");
95puts("");
96}
97else
98{
99char str[256];
100
101sprintf(str, "cpm: ioctl device %s", buf[intrface].ifr_name);
102
103perror(str);
104}
105}
106}
107else
108perror("cpm: ioctl");
109}
110else
111perror("cpm: socket");
112
113close(fd);
114return retn;
115}</unistd.h></arpa></net></netinet></net></sys></sys></sys></sys></stdio.h>