Do we need to include both <netinet/in.h> and <arpa/inet.h> headers? What is the difference between them?

Viewed 4292

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?

2 Answers

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.

They are different headers. If you need definitions from both, include both.

Their contents are documented in Posix:

netinet/in.h is allowed to include all of arpa/inet.h, and vice versa. But it is not guaranteed and you should not rely on it. As documented, some (but not all) symbols are required to be declared in both.

Related