我的获取IP地址C功能未输出正确的值

时间:2013-10-04 02:03:07

标签: c networking

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

1 个答案:

答案 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)
);

你也可以摆脱循环。