0

I am a newbie to socket programming. I want to know why we need to do casting like this (struct sockaddr *) &servAddrbind when we bind a socket:

bind (sockfd, (struct sockaddr *) &servAddr, sizeof(servAddr));

Why can't we do binding without such cast?

red0ct
  • 4,840
  • 3
  • 17
  • 44
Thisura
  • 23
  • 5
  • 4
    Take a look at the answers to ["Why do we cast sockaddr\_in to sockaddr when calling bind()?"](https://stackoverflow.com/questions/21099041/why-do-we-cast-sockaddr-in-to-sockaddr-when-calling-bind) In short, `bind` can work with multiple types of socket address, but a function can't accept more than one type for the same argument, so you have to cast your socket address to the generic `sockaddr` to pass it in. – jirassimok Oct 03 '19 at 02:45
  • thank you for your quick reply i just want why we need to casting in generic socket address structure rather than doing like this "int bind (socket, localaddr, addrlen)" which we do in ANSI C function – Thisura Oct 03 '19 at 03:05
  • 1
    It's because the second argument of `bind` must be a pointer to a `struct sockaddr`, but you are actually passing in a pointer to a `struct sockaddr_in` or some other type of address struct. – jirassimok Oct 03 '19 at 03:10

0 Answers0