1

The unix domain sockets address structure is defined as:

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

And I see 2 ways of calculating the size, which later on is passed to bind

  1. From APUE and http://beej.us/guide/bgipc/html/multi/unixsock.html
//beej's guide
struct sockaddr_un local;
int len;

len = strlen(local.sun_path) + sizeof(local.sun_family);
bind(s, (struct sockaddr *)&local, len);

//APUE
struct sockaddr_un un;
size = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);
bind(fd, (struct sockaddr *)&un, size)
  1. The Linux Progamming Interface
const char *SOCKNAME = "/tmp/mysock";
struct sockaddr_un addr;
addr.sun_family = AF_UNIX; /* UNIX domain address */
strncpy(addr.sun_path, SOCKNAME, sizeof(addr.sun_path) - 1);
bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un))

Which way is correct? (Maybe both are correct?)

Rick
  • 7,007
  • 2
  • 49
  • 79
  • 1
    See [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) to learn why Beej's guide variant is incorrect. Both APUE's variant and using `sizeof` on the whole structure works. – Some programmer dude Dec 22 '19 at 11:14
  • @Someprogrammerdude Put aside the incorrect form first. If both APUE's variant and `sizeof` on the whole structure works, why bother to write the APUE's variant? `size = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);` looks horrible – Rick Dec 22 '19 at 11:23
  • APUE is rather old now (originally published in 1992), it might have been a good solution back then. – Some programmer dude Dec 22 '19 at 11:26
  • @Someprogrammerdude OK then let me guess: is it the `bind` function in the past that needs the specific size of each address member size, while the newer `bind` can accept the whole `sizeof` with padding? – Rick Dec 22 '19 at 11:32
  • That's a possible interpretation. – Some programmer dude Dec 22 '19 at 11:38
  • By the way that last variant (from The Linux Programming Interface) is incorrect as well, as it might not add a terminating null character in the `sun_path` array, *and* let the last element of it be uninitialized. – Some programmer dude Dec 22 '19 at 11:40
  • 1
    @Someprogrammerdude I checked the `offsetof` function usage and my guess above is wrong. Both the APUE variant and `sizeof` the whole structure pass enough bytes (both includes padding bytes) to `bind`, while Beej's variant might not pass enough bytes for `sockaddr_un.sun_family`. And I don't see much difference between the APUE variant and `sizeof` the whole structure :) – Rick Dec 22 '19 at 13:36

1 Answers1

0

the correct way is to use sizeof (struct sockaddr_un) actually.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Luis Colorado
  • 10,974
  • 1
  • 16
  • 31