Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe reinterpret_cast with sockaddr?

Assume I'm doing some socket programming:

struct sockaddr_in sa;
inet_pton(AF_INET, "127.0.0.1", &(sa.sin_addr));
auto *resa = reinterpret_cast<struct sockaddr*>(&sa);
bind(sfd, resa, sizeof(sa));

Now the question is: we do reinterpret_cast (or C-style (struct sockaddr *) cast like in tutorials or man) yet the standard does not guarantee that to work, right? On the other hand there does not seem to be a way to do that differently, bind() requires struct sockaddr* (and it has to access the underlying struct to determine what it received).

So is it safe to do reinterpret_cast between different types in this case? If yes then why?

like image 871
freakish Avatar asked May 27 '17 20:05

freakish


1 Answers

The ability to support many kinds of pointer manipulation is regarded by the Standard as a Quality of Implementation issue. The Standard does not mandate that all implementations be suitable for low-level or systems programming, but quality implementations suitable for such purpose on e.g. Unix should support the kinds of semantics typically used by systems code on such platform. An implementation could be incapable of handling code that treats shared parts of structures in type-agnostic fashion and yet still be a high-quality implementation for some specialized purposes that don't involve any low-level or systems programming. On the other hand, a quality implementation suitable for low-level programming should have no trouble handling such code. Any implementation that can't handle such code should be viewed as being a low-quality implementation and/or unsuitable for low-level programming, and a low-level program's inability to work with such implementations is not a defect.

like image 188
supercat Avatar answered Sep 21 '22 17:09

supercat