7

I'm building a simple socket web server using the sys/socket.h lib, and I came across the socklen_t and sa_family_t data types and am a bit confused on what their actual purpose is.

Definition:

  • sa_family_t - unsigned integer type.
  • socklen_t - an unsigned opaque integer type of length of at least 32-bits.

Now I understand that the <sys/socket> lib declares three structures (sockaddr,msghdr,cmsghdr) which contain members that declare these data types.

  • sa_family_t sa_family address family
  • socklen_t msg_namelen size of address
  • socklen_t msg_controllen ancillary data buffer len
  • socklen_t cmsg_len data byte count, including the cmsghdr

But why create new data types, why not just use an unsigned int data type?

Dimen
  • 391
  • 1
  • 4
  • 18
Jordan Davis
  • 1,485
  • 7
  • 21
  • 40

1 Answers1

9

By declaring specific types for these fields, it decouples them from a particular representation like unsigned int.

Different architectures can be free to define different sizes for these fields, and code that uses these specific types doesn't need to worry about how big an int is on a given machine.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Ok yea thats makes sense... so basically when it says "at least" 32-bits, it's implying that it "could" be greater, and that would be arch based, correct? – Jordan Davis Sep 15 '15 at 18:11
  • 1
    Correct. Similarly for `size_t` as well. – dbush Sep 15 '15 at 18:20
  • Cool perfect, and makes sense why it recommends not using anything higher than `2^32-1` if you want to port it between 32/64-bit systems. Thanks for the help I really appreciate it! – Jordan Davis Sep 15 '15 at 18:23