0

struct rtentry

The following

#include <net/route.h>
#include <netinet/in.h>
int main(){
  struct rtentry e={};
  *((struct sockaddr_in*)(&(e.rt_genmask)))=(struct sockaddr_in){.sin_family=AF_INET,.sin_port=0,.sin_addr=INADDR_ANY};
  return 0;
}

gives the warning (gcc -std=c11 -Wall test.c)

test.c:5:45: warning: missing braces around initializer [-Wmissing-braces]
    5 |   *((struct sockaddr_in*)(&(e.rt_genmask)))=(struct sockaddr_in){.sin_family=AF_INET,.sin_port=0,.sin_addr=INADDR_ANY};
      |                                             ^
                                         ^

Why? How may I fix the code?

5
  • rtenty or rtentry? I found latter in route.h. Commented Aug 21, 2020 at 3:51
  • Please provide a Minimal Reproducible Example. Commented Aug 21, 2020 at 3:53
  • It copmiles if I use C compiler. godbolt.org/z/xKETe3 . But if I switch to C++ compiler, there is error not warning. Commented Aug 21, 2020 at 5:07
  • @LouisGo -Wall Commented Aug 21, 2020 at 5:59
  • 2
    .sin_addr={INADDR_ANY} - sin_addr is a composite. This will also make it c++ friendly. Commented Aug 21, 2020 at 6:45

1 Answer 1

1
  1. INADDR_ANY is macro defined.
  2. in_addr is a struct for wrapping value. You need to use .sin_addr={INADDR_ANY} to make sure it's initialized by value INADDR_ANY.
           struct sockaddr_in {
               sa_family_t    sin_family; /* address family: AF_INET */
               in_port_t      sin_port;   /* port in network byte order */
               struct in_addr sin_addr;   /* internet address */
           };

           /* Internet address. */
           struct in_addr {
               uint32_t       s_addr;     /* address in network byte order */
           };

Fixed: https://godbolt.org/z/xM8r1E

#include <net/route.h>

int main(void) {
    struct rtentry e={};
    *(struct sockaddr_in*)(&(e.rt_dst))=(struct sockaddr_in){
    .sin_family=AF_INET,
    .sin_port=0,
    .sin_addr={INADDR_ANY}
    };
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.