Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the address length parameter neccessary when binding a socket in C?

I started playing around with sockets in C and when i bind a socket to an address using bind() system call i have to specify the addrlen parameter.

Why is the address length necessary in a socket?

like image 254
giomanda Avatar asked Oct 17 '25 16:10

giomanda


2 Answers

The bind function (syscall) is generic function which have to cope with several type of addresses, IPv4, IPv6, bluetooth, unix sockets and ... each address type may have different size than others, so you have to make it clear for bind which address you're passing by passing its size.

bind is a syscall, syscall is just a wrapper function which is used in userspace for interacting with kernel space. when you create a socket via socket syscalls a record will be created in file descriptor table of calling process. the record itself includes the type of socket. when you call bind and passing address to it, the address should be copied to kernel space, but how much big is address? the bind syscall doesn't know the socket you're binding, because the socket record created in kernel space and userspace bind function and its respective syscall doesn't know about the size it requires. actually the bind is just syscall which copies address data to kernel space and notifies the kernel about it.

In the other hand, the bind could not determine address time at runtime, because there is no runtime type checking in pure C.

so at this time the bind doesn't know about the addresses and you should specify the address size, so the address structure will be copied to kernel space completely.

like image 77
e.jahandar Avatar answered Oct 19 '25 13:10

e.jahandar


There are several different sorts of socket addresses

These each have their own sockaddr_* structure, i.e. sockaddr_in for AF_INET, sockaddr_in6 for AF_INET6, etc.

Passing the length allows the kernel to check that the passed data is consistent with the socket type.

like image 42
Alnitak Avatar answered Oct 19 '25 13:10

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!