I want to use the htonl
function in my ruby c extension, but don't want to use any of the other internet stuff that comes with it. What would be the most minimalistic file to #include
that is still portable? Looking through the header files on my computer, I can see that either machine/endian.h
or sys/_endian.h
would let me use them, although I am not sure if that is a good idea.
Asked
Active
Viewed 3.8k times
21

Adrian
- 14,931
- 9
- 45
- 70
2 Answers
17
The standard header is:
#include <arpa/inet.h>
You don't have to worry about the other stuff defined in that header. It won't affect your compiled code, and should have only a minor effect on compilation time.
EDIT: You can test this. Create two files, htonl_manual.c
// non-portable, minimalistic header
#include <byteswap.h>
#include <stdio.h>
int main()
{
int x = 1;
x = __bswap_32(x);
printf("%d\n", x);
}
and htonl_include.c:
// portable
#include <arpa/inet.h>
#include <stdio.h>
int main()
{
int x = 1;
x = htonl(x);
printf("%d\n", x);
}
Assemble them at -O1, then take the difference:
gcc htonl_manual.c -o htonl_manual.s -S -O1
gcc htonl_include.c -o htonl_include.s -S -O1
diff htonl_include.s htonl_manual.s
For me, the only difference is the filename.

Matthew Flaschen
- 278,309
- 50
- 514
- 539
-
Thanks! I didn't know that it wouldn't change the compiled code. Before you answered, I was considering writing my own version just so that my code could stay small. – Adrian Jul 04 '10 at 03:46
9
On Windows, arpa/inet.h
doesn't exist so this answer won't do. The include is:
#include <winsock.h>
So a portable version of the include block (always better to provide one):
#ifdef _WIN32
#include <winsock.h>
#else
#include <arpa/inet.h>
#endif

Jean-François Fabre
- 137,073
- 23
- 153
- 219
-
1is there any portable single include available in c++? or do we also have to #ifdef – ljleb Aug 23 '22 at 04:54
-
not going to happen apparently https://stackoverflow.com/questions/6638213/will-and-should-there-be-sockets-in-c11 – Jean-François Fabre Aug 23 '22 at 05:52
-
1right. Just letting you know I time traveled 2 years in the past and commented on [this](https://stackoverflow.com/a/61319938/9906706) particular answer – ljleb Aug 23 '22 at 05:59