How to enumerate all IP addresses attached to a machine, in POSIX C?

前端 未结 6 859
遥遥无期
遥遥无期 2021-01-03 03:25

Background:

I\'m writing a daemon that makes outgoing TCP/IP connections. It will be running on machines with multiple (non-loopback) IP addresses.

6条回答
  •  一整个雨季
    2021-01-03 04:01

    This can only be done in an operating system dependent fashion. You could try parsing the output of 'iptables', but the right answer for linux is to use ioctl.

    SIOCGIFCONF  takes  a  struct  ifconf *.  The ifc_buf field points to a
          buffer of length ifc_len bytes, into which the kernel writes a list of
          type struct ifreq [].
    

    The struct ifreq is documented in linux/if.h:

    struct ifreq 
    {
    #define IFHWADDRLEN     6
            union
            {
                    char    ifrn_name[IFNAMSIZ];            /* if name, e.g. "en0" */
            } ifr_ifrn;
    
            union {
                    struct  sockaddr ifru_addr;
                    struct  sockaddr ifru_dstaddr;
                    struct  sockaddr ifru_broadaddr;
                    struct  sockaddr ifru_netmask;
                    struct  sockaddr ifru_hwaddr;
                    short   ifru_flags;
                    int     ifru_ivalue;
                    int     ifru_mtu;
                    struct  ifmap ifru_map;
                    char    ifru_slave[IFNAMSIZ];   /* Just fits the size */
                    char    ifru_newname[IFNAMSIZ];
                    void *  ifru_data;
                    struct  if_settings ifru_settings;
            } ifr_ifru;
    };
    

    As you can see, it contains the address information you desire.

提交回复
热议问题