#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if_arp.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <iostream>
using namespace std;
//from http://rainfish.cublog.cn/
//by ben
int main()
{
int sock;
struct ifconf conf;
struct ifreq *ifr;
char buff[BUFSIZ];
int num;
int i;
int ret = 0;
sock = socket(PF_INET, SOCK_DGRAM, 0);
conf.ifc_len = BUFSIZ;
conf.ifc_buf = buff;
/*
SIOCGIFCONF
返 回系统中配置的所有接口的配置信息。
*/
ioctl(sock, SIOCGIFCONF, &conf);
num = conf.ifc_len / sizeof(struct ifreq);
ifr = conf.ifc_req;
cout << "ip's num " << num << endl;
string str_ip;
for (i = 0; i < num; i++)
{
struct sockaddr_in *sin = (struct sockaddr_in *) (&ifr->ifr_addr);
// SIOCGIFFLAGS 可以获取接口标志。
ioctl(sock, SIOCGIFFLAGS, ifr);
//cout << "ifr->ifr_flags: " << ifr->ifr_flags << endl;
if (((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP))
{
str_ip = inet_ntoa(sin->sin_addr);
cout << "ip is " << str_ip << endl;
}
ifr++;
}
}
|