#include <sys/types.h>
#include <ifaddrs.h>
int getifaddrs(struct ifaddrs **ifap);
void freeifaddrs(struct ifaddrs *ifa);
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;
#defineifa_broadaddr ifa_ifu.ifu_broadaddr
#defineifa_dstaddr ifa_ifu.ifu_dstaddr
void*ifa_data;/* Address-specific data */
};
如果ifa_name不是网络站点(例如can总线接口)的时候,ifa_addr为NULL,
在没有设置IP地址的情况下,ifa_addr的地址簇不为AF_INET。
#include <ifaddrs.h>
#include <stdio.h>
#include <arpa/inet.h>
int main()
{
struct ifaddrs *ifa, *temp;
printf("%d\n", getifaddrs(&ifa));
for (temp = ifa; temp != NULL; temp = temp->ifa_next) {
if (temp->ifa_addr == NULL)
continue;
if (AF_PACKET == temp->ifa_addr->sa_family) {
printf("%s\n", temp->ifa_name);
} else if (AF_INET == temp->ifa_addr->sa_family) {
printf("%s:", temp->ifa_name);
printf("%s\n", inet_ntoa(((struct sockaddr_in *)(temp->ifa_addr))->sin_addr));
}
}
freeifaddrs(ifa);
return 0;
}