0

Can someone explain to me the purpose of this line of code, especially the
(struct sockaddr *)&host_addr parameter?

bind(sockfd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr));
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
pedro santos
  • 337
  • 1
  • 2
  • 9
  • `host_addr` contains the local address and port of the socket. For a server, this is the port that it listens for incoming connections on. – Barmar Sep 19 '16 at 01:11
  • Are you asking why it uses the `(struct sockaddr *)` cast? – Barmar Sep 19 '16 at 01:11
  • what about the (struct sockaddr *) part? – pedro santos Sep 19 '16 at 01:11
  • 1
    It binds the socket to the address specified in the host address. The host address structures are plain weird — they predate `void *`, but nowadays, that's what would be used if the interface was (re)designed from scratch. So, instead of `void *`, the `struct sockaddr *` type is used, but the values passed are different types (an IPv4 address uses less space than an IPv6 one, and both are different from a 'Unix-domain' socket address, aka filename), as a uniform pointer type. Hence the cast. – Jonathan Leffler Sep 19 '16 at 01:12
  • See http://stackoverflow.com/questions/21099041/why-do-we-cast-sockaddr-in-to-sockaddr-when-calling-bind – Barmar Sep 19 '16 at 01:12
  • yes i dont understand that part – pedro santos Sep 19 '16 at 01:12

0 Answers0