1 /* Test hton/ntoh functions.
2 Copyright (C) 1997-2022 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19 #include <endian.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <netinet/in.h>
23
24 #if BYTE_ORDER == BIG_ENDIAN
25 # define TEST(orig, swapped, fct) \
26 if ((fct (orig)) != (orig)) { \
27 printf ("Failed for %s -> %#x\n", #fct "(" #orig ")", fct (orig)); \
28 result = 1; \
29 }
30 #elif BYTE_ORDER == LITTLE_ENDIAN
31 # define TEST(orig, swapped, fct) \
32 if ((fct (orig)) != (swapped)) { \
33 printf ("Failed for %s -> %#x\n", #fct "(" #orig ")", fct (orig)); \
34 result = 1; \
35 }
36 #else
37 # error "Bah, what kind of system do you use?"
38 #endif
39
40 uint32_t lo = 0x67452301;
41 uint16_t foo = 0x1234;
42
43 int
main(void)44 main (void)
45 {
46 int result = 0;
47
48 TEST (0x67452301, 0x01234567, htonl);
49 TEST (0x67452301, 0x01234567, (htonl));
50 TEST (0x67452301, 0x01234567, ntohl);
51 TEST (0x67452301, 0x01234567, (ntohl));
52
53 TEST (lo, 0x01234567, htonl);
54 TEST (lo, 0x01234567, (htonl));
55 TEST (lo, 0x01234567, ntohl);
56 TEST (lo, 0x01234567, (ntohl));
57
58 TEST (0x1234, 0x3412, htons);
59 TEST (0x1234, 0x3412, (htons));
60 TEST (0x1234, 0x3412, ntohs);
61 TEST (0x1234, 0x3412, (ntohs));
62
63 TEST (foo, 0x3412, htons);
64 TEST (foo, 0x3412, (htons));
65 TEST (foo, 0x3412, ntohs);
66 TEST (foo, 0x3412, (ntohs));
67
68 return result;
69 }
70