Home > Software engineering >  What's the default value of the structure in_addr for the field s_addr?
What's the default value of the structure in_addr for the field s_addr?

Time:11-28

I have made a tiny client/server app, but I was wondering if the default value of the field s_addr was INADDR_ANY or not as when I don't specify an address for the socket, for both the client and the server, it works the same as with this flag given in the structure. I haven't find anything on the doc about that

struct sockaddr_in {
    short            sin_family;   
    unsigned short   sin_port;     
    struct in_addr   sin_addr;     
};
struct in_addr {
    unsigned long s_addr;         
};

CodePudding user response:

The default value is "undefined", i.e. the initial state of the struct depends on the pre-existing state of the bytes it occupies in RAM (which in turn will depend on what those memory-locations were previously used for earlier in your program's execution). Obviously you can't depend on that behavior, so you should always set the fields to some appropriate well-known value before using the struct for anything.

A convenient way to ensure that all fields of the struct are set to all-zeros would be: memset(&myStruct, 0, sizeof(myStruct));

CodePudding user response:

In addition to Jeremy Friesner's answer, you can use

struct sockaddr_in addr ={0};

declaring and initializing the struct in one go so you do not forget to zero it. I believe this been valid since C99; in C23 you will also be able to omit the 0; so struct sockaddr_in addr ={}; would also work.

But my favourite approach is to use designated initializers (valid since C99) like so:

struct sockaddr_in addr ={
    .sin_family = AF_INET, 
    .sin_addr.s_addr = htonl(INADDR_ANY),
    .sin_port = htons(PORT)
};

The fields you do not explicitly initialize, will be zeroed.

What is a designated initializer in C?

  • Related