4

I have seen the question similar question below:

struct sockaddr_un v/s sockaddr - C(Linux)

But I am still very unclear about what the difference is between sockaddr_in and sockaddr, every socket method/function I.e bind, connect, seems to use sockaddr and not sockaddr_in, are these structures interchangeable? if only sockaddr is used then why is there the _in one? I prefer the _in seems more detailed and sorted.

Delete the post or so if I have broken any rules ;(

most of the time the 3rd parameter is the addr_len is this used to quickly differentiate between ipv4 and ipv6?

Community
  • 1
  • 1
iBeyondPower
  • 357
  • 1
  • 5
  • 8

2 Answers2

9

The sockaddr is a generic socket address. If you remember, you can create TCP/IPv4, UDP/IPv4, UNIX, TCP/IPv6, UDP/IPv6 sockets (and more!) through the same operating system API - socket().

All of these different socket types have different actual addresses - composed of different fields.

sockaddr_in is the actual IPv4 address layout (it has .sin_port and .sin_addr). A UNIX domain socket will have type sockaddr_un and will have different fields defined, specific to the UNIX socket family.

Basically sockaddr is a collection of bytes, it's size being the maximum of sizes of all supported (by the O/S) socket/address families such that it can hold all of the supported addresses.

emvee
  • 4,371
  • 23
  • 23
1

Taking a look at sockaddr_in

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)];
  };

And if we see sockaddr

* Structure describing a generic socket address.  */
struct sockaddr
  {
    __SOCKADDR_COMMON (sa_);    /* Common data: address family and length.  */
    char sa_data[14];       /* Address data.  */
  };

So actually, they are not exchangeable, but but they have the same size so you can use it with no problem and cast between those structures.

But remember you must know what you are doing or probably will get segfaults or unexpected behavior.

Jose Palma
  • 756
  • 6
  • 13
  • thank you, but then since every socket method uses sockaddr, i cannot use sockaddr_in? Since u say they are not interchangeable, then what is the use of sockaddr_in? – iBeyondPower Apr 15 '15 at 12:00
  • is the addr_len used to differentiate between ipv4 and ipv6 or used to discriminate the padding o.O – iBeyondPower Apr 15 '15 at 12:05
  • This is bogus. This is not the reason why those structs are different or explanation what the difference between them is. – emvee Apr 15 '15 at 13:22