这是获取和输出无线en1的IP地址的功能。
char* getIPAddress(char* src)
{
struct ifaddrs *ifaddr, *ifa;
int family;
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(EXIT_FAILURE);
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
if (0 == strcmp(ifa->ifa_name,"en1" ) && (family == AF_INET)) { // v4
// en1
inet_ntop(ifa->ifa_addr->sa_family,&((struct sockaddr_in*)ifa)->sin_addr,src,sizeof(struct sockaddr_in));
}
}
freeifaddrs(ifaddr);
return src;
}
我会期待129.10.10.50或类似的东西,但现在它输出空白。
答案 0 :(得分:2)
这是不正确的:
inet_ntop(
ifa->ifa_addr->sa_family,
&((struct sockaddr_in*)ifa)->sin_addr, // <--- casting wrong variable
src,
sizeof(struct sockaddr_in)
);
您将struct ifaddrs
投射到struct sockaddr_in
而不是它的成员:
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 */ // <--- this one
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 */
};
这将解决它:
inet_ntop(
ifa->ifa_addr->sa_family,
&((struct sockaddr_in*)ifa->ifa_addr)->sin_addr, // ifa_addr member instead
src,
sizeof(struct sockaddr_in)
);
你也可以摆脱循环。