casting between sockaddr and sockaddr_in

后端 未结 3 2038
独厮守ぢ
独厮守ぢ 2021-01-13 13:02

I came across a socket programming tutorial in which it is quoted

\"a pointer to a struct sockaddr_in can be cast to a pointer to a struct sockad

3条回答
  •  有刺的猬
    2021-01-13 13:17

    The different sizes don't matter. Just like you can pass strings of different lengths to the various string-handling functions, you can pass struct sockaddr of different lengths to the various socket-handling functions.

    The size of the struct sockaddr is interpreted by the called function per the contents of the sa_family member of the structure. Note also that all functions that take a struct sockaddr * address also take a socklen_t argument that holds the size of the structure being passed.

    For example, the struct sockaddr_un structure is 110 bytes:

       struct sockaddr_un {
           sa_family_t sun_family;               /* AF_UNIX */
           char        sun_path[108];            /* pathname */
       };
    

    The called function such as bind() or getpeername() have declarations similar to

    int getpeerame(int sockfd, struct sockaddr *addr, socklen_t *addrlen); 
    

    for the very reason that the size(s) of various socket structures vary.

    Note that the first member of every struct sockaddr_??? is the sa_family. Thus it's always in the same place.

提交回复
热议问题