cheader-filesdarwin

Why net/if.h before ifaddrs.h?


Apple's man page for getifaddrs says, under "BUGS",

If both <net/if.h> and <ifaddrs.h> are being included, <net/if.h> must be included before <ifaddrs.h>.

Why is this? This looks to be an Apple thing as there's no such caveat in the Linux man page.

Apple's ifaddrs.h (at least, on my machine) contains this section:

/*
 * This may have been defined in <net/if.h>.  Note that if <net/if.h> is
 * to be included it must be included before this header file.
 */
#ifndef ifa_broadaddr
#define ifa_broadaddr   ifa_dstaddr /* broadcast address interface */
#endif

However, my net/if.h doesn't define ifa_broadaddr so it's not clear what the conflict would be.


Solution

  • <net/if.h> includes <net/if_var.h>:

    #include <net/if_var.h>
    

    And <net/if_var.h> defines it:

    #define ifa_broadaddr   ifa_dstaddr     /* broadcast address interface */
    

    Note that this definition is always (re)defined in <net/if_var.h>.

    The definition in <ifaddrs.h> is surrounded by #ifndef and #endif tags to prevent redefinition, which means it can use an alternative definition if it was already defined.

    From the very same documentation you linked:

    Note that as a convenience, ifa_broadaddr is defined by a compiler #define directive to be the same as ifa_dstaddr.

    By including <net/if.h> (and thus also <net/if_var.h>) before <ifaddrs.h>, you ensure the definition of ifa_broadaddr matches.