0

这是我获取和输出无线 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 或类似的东西,但现在它输出空白。

4

1 回答 1

2

这是不正确的:

inet_ntop(
    ifa->ifa_addr->sa_family,
    &((struct sockaddr_in*)ifa)->sin_addr, // <--- casting wrong variable
    src,
    sizeof(struct sockaddr_in)
);

您正在投射struct ifaddrsstruct 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)
);

你也可以跳出循环。

于 2013-10-04T02:21:10.133 回答