/*
* main.c
* ----------------------------------------------
* 2013-01-09 chrisniu1984@gmail.com
*
* [BUILD]
* gcc -o main main.c -Wall
*
*/
#include <stdio.h>
#include <netdb.h>
#include <ifaddrs.h>
// 系统定义的结构,贴在这里方便大家查阅,也可man getifaddrs查看。
// struct ifaddrs {
// struct ifaddrs *ifa_next; /* Next item in list */
// char *ifa_name; /* Name of interface */
// unsigned int ifa_flags; /* Flags from SIOCGIFFLAGS */
// struct sockaddr *ifa_addr; /* Address of interface */
// struct sockaddr *ifa_netmask; /* Netmask of interface */
// union {
// struct sockaddr *ifu_broadaddr;
// /* Broadcast address of interface */
// struct sockaddr *ifu_dstaddr;
// /* Point-to-point destination address */
// } ifa_ifu;
// #define ifa_broadaddr ifa_ifu.ifu_broadaddr
// #define ifa_dstaddr ifa_ifu.ifu_dstaddr
// void *ifa_data; /* Address-specific data */
// };
int main(int argc, char **argv)
{
struct ifaddrs *ifa;
if (getifaddrs(&ifa) != 0) {
return -1;
}
struct ifaddrs *next = ifa;
for (; next!=NULL; next=next->ifa_next) {
struct sockaddr_in *sin = (struct sockaddr_in*)next->ifa_addr;
if (sin->sin_family != AF_INET) {
continue;
}
unsigned char *b = (unsigned char *)(&sin->sin_addr.s_addr);
printf("%s\t%u.%u.%u.%u\n", next->ifa_name, b[0], b[1], b[2], b[3]);
}
freeifaddrs(ifa);
return 0;
}