giomanda
giomanda

Reputation: 177

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?

Upvotes: 4

Views: 1676

Answers (4)

e.jahandar
e.jahandar

Reputation: 1763

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.

Upvotes: 3

leuage
leuage

Reputation: 566

bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr))

It takes three arguments, the socket file descriptor, the address to which is bound, and the size of the address to which it is bound

Why is the address length necessary in a socket?

Its a limit in which it is bound

for example i will handle it is as below

if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
          { 
           error("ERROR on binding");
          }

Upvotes: 0

Ctx
Ctx

Reputation: 18420

The syscalls are protocol independent, for example they apply to

  • IPv4 (sockaddr_in)
  • IPv6 (sockaddr_in6)
  • Unix Domain Sockets (sockaddr_un)

all of which may have different lengths of their socket description. This is why you have to specify the length of the corresponding structure.

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

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.

Upvotes: 3

Related Questions