Socket programming sockaddr_in, in_addr structure

Asked 2 years ago, Updated 2 years ago, 64 views

int main(int argc, char* argv[])
{

    struct sockaddr_in addr1, addr2;
    char* str_ptr;
    char str_arr[20];

    addr1.sin_addr.s_addr = htonl(0x10203040);
}

where s_addr is the variable declared in the in_addr structure.

What I'm curious about is why it's not an error when the in_addr structure has not even been declared?

(Excerpt part of the book code.)

The header file declared stdio.h, string.h, arpa/inet.h.

socket network c

2022-09-20 11:36

1 Answers

If you check https://man7.org/linux/man-pages/man7/ip.7.html, sockaddr_in is defined as follows.

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 */
};

In fact, if you look at Linux's /usr/include/netinet/in.h header, it is defined as follows:

typedef uint32_t in_addr_t;
struct in_addr
  {
    in_addr_t s_addr;
  };

struct sockaddr_in
  {
    __SOCKADDR_COMMON (sin_);
    in_port_t sin_port;                 /* Port number.  */
    struct in_addr sin_addr;            /* Internet address.  */

    /* /* Pad to size of `struct sockaddr'.  */
    unsigned char sin_zero[sizeof (struct sockaddr)
                           - - __SOCKADDR_COMMON_SIZE
                           - - sizeof (in_port_t)
                           - - sizeof (struct in_addr)];
  };

If you look at the above codes, the structure sockaddr_in has the member variable sin_addr. This variable sin_addr has a s_addr member variable because it is a in_addr structure.

Therefore, addr1 has sin_addr, and this sin_addr has s_addr, so you can access addr1.sin_addr.s_addr in a series.


2022-09-20 11:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.