Back to index

glibc  2.9
htontest.c
Go to the documentation of this file.
00001 /* Test hton/ntoh functions.
00002    Copyright (C) 1997, 2002 Free Software Foundation, Inc.
00003    This file is part of the GNU C Library.
00004    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
00005 
00006    The GNU C Library is free software; you can redistribute it and/or
00007    modify it under the terms of the GNU Lesser General Public
00008    License as published by the Free Software Foundation; either
00009    version 2.1 of the License, or (at your option) any later version.
00010 
00011    The GNU C Library is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014    Lesser General Public License for more details.
00015 
00016    You should have received a copy of the GNU Lesser General Public
00017    License along with the GNU C Library; if not, write to the Free
00018    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00019    02111-1307 USA.  */
00020 
00021 #include <endian.h>
00022 #include <stdio.h>
00023 #include <sys/types.h>
00024 #include <netinet/in.h>
00025 
00026 #if BYTE_ORDER == BIG_ENDIAN
00027 # define TEST(orig, swapped, fct) \
00028   if ((fct (orig)) != (orig)) {                                             \
00029     printf ("Failed for %s -> %#x\n", #fct "(" #orig ")", fct (orig));             \
00030     result = 1;                                                             \
00031   }
00032 #elif BYTE_ORDER == LITTLE_ENDIAN
00033 # define TEST(orig, swapped, fct) \
00034   if ((fct (orig)) != (swapped)) {                                   \
00035     printf ("Failed for %s -> %#x\n", #fct "(" #orig ")", fct (orig));             \
00036     result = 1;                                                             \
00037   }
00038 #else
00039 # error "Bah, what kind of system do you use?"
00040 #endif
00041 
00042 u_int32_t lo = 0x67452301;
00043 u_int16_t foo = 0x1234;
00044 
00045 int
00046 main (void)
00047 {
00048   int result = 0;
00049 
00050   TEST (0x67452301, 0x01234567, htonl);
00051   TEST (0x67452301, 0x01234567, (htonl));
00052   TEST (0x67452301, 0x01234567, ntohl);
00053   TEST (0x67452301, 0x01234567, (ntohl));
00054 
00055   TEST (lo, 0x01234567, htonl);
00056   TEST (lo, 0x01234567, (htonl));
00057   TEST (lo, 0x01234567, ntohl);
00058   TEST (lo, 0x01234567, (ntohl));
00059 
00060   TEST (0x1234, 0x3412, htons);
00061   TEST (0x1234, 0x3412, (htons));
00062   TEST (0x1234, 0x3412, ntohs);
00063   TEST (0x1234, 0x3412, (ntohs));
00064 
00065   TEST (foo, 0x3412, htons);
00066   TEST (foo, 0x3412, (htons));
00067   TEST (foo, 0x3412, ntohs);
00068   TEST (foo, 0x3412, (ntohs));
00069 
00070   return result;
00071 }