Doesn't one make the other visible? What is the difference between them and when to use what? My professor has provided me with a starter code and he has used <netinet/in.h>
in the server socket and <arpa/inet.h>
in the client. Is there a reason for that?
The netinet/in. h header file contains definitions for the internet protocol family. The following structure definition is supported for IPv6: struct ip6_mtuinfo{};
Socket header files contain data definitions, structures, constants, macros, and options used by socket subroutines. Defines Internet constants and structures. Contains Internet name server information.
This is a common pattern in C libraries: header A defines some stuff, header B defines some stuff, but header A also requires some stuff from header B, so it includes B on its own.
So if you include only header A, your code will still compile even if you use stuff from header B. This appears to be the case with arpa/inet.h
including netinet/in.h
. So no, you don't "need" to include both.
BUT
Even though including A might include B as a side-effect, that is really just an implementation detail and may not be something guaranteed by the header. In other words, your code might compile fine on your machine but fail to compile on another standards-compliant machine with slightly different header implementations.
Another situation where this can bite you is with code refactoring. Way down the line you might restructure in some way that your code no longer calls inet_addr
or anything else from arpa/inet.h
. "Oh, I can remove that header now!" you might think... only for your code to stop compiling because you still use sockaddr_in
somewhere and you never included netinet/in.h
directly.
(You need to read the documentation to see what a header is guaranteed to provide by the standard: arpa/inet.h, netinet/in.h)
Or maybe some poor newbie is looking at your code for guidance years later. They know nothing about this networking magic and they see INADDR_BROADCAST
and sa_family_t
and they are so confused. Because these symbols are being defined as an implementation-specific side-effect of arpa/inet.h
!
So, again, you don't "need" to include both. But it's a good idea to do it anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With