addr.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /* Copyright (C) 1995,1996 Robert de Bath <rdebath@cix.compulink.co.uk>
  2. * This file is part of the Linux-8086 C library and is distributed
  3. * under the GNU Library General Public License.
  4. */
  5. /*
  6. * Manuel Novoa III Dec 2000
  7. *
  8. * Converted to use my new (un)signed long (long) to string routines, which
  9. * are smaller than the previous functions and don't require static buffers.
  10. * In the process, removed the reference to strcat and cut object size of
  11. * inet_ntoa in half (from 190 bytes down to 94).
  12. */
  13. #define __FORCE_GLIBC__
  14. #include <features.h>
  15. #include <string.h>
  16. #include <ctype.h>
  17. #include <netinet/in.h>
  18. int inet_aton(const char *cp, struct in_addr *inp);
  19. #ifdef L_inet_aton
  20. int inet_aton(cp, inp)
  21. const char *cp;
  22. struct in_addr *inp;
  23. {
  24. unsigned long addr;
  25. int value;
  26. int part;
  27. if (!inp)
  28. return 0;
  29. addr = 0;
  30. for (part = 1; part <= 4; part++) {
  31. if (!isdigit(*cp))
  32. return 0;
  33. value = 0;
  34. while (isdigit(*cp)) {
  35. value *= 10;
  36. value += *cp++ - '0';
  37. if (value > 255)
  38. return 0;
  39. }
  40. if (*cp++ != ((part == 4) ? '\0' : '.'))
  41. return 0;
  42. addr <<= 8;
  43. addr |= value;
  44. }
  45. inp->s_addr = htonl(addr);
  46. return 1;
  47. }
  48. #endif
  49. #ifdef L_inet_addr
  50. unsigned long inet_addr(cp)
  51. const char *cp;
  52. {
  53. struct in_addr a;
  54. if (!inet_aton(cp, &a))
  55. return -1;
  56. else
  57. return a.s_addr;
  58. }
  59. #endif
  60. #ifdef L_inet_ntoa
  61. #include <limits.h>
  62. #if (ULONG_MAX >> 32)
  63. /* We're set up for 32 bit unsigned longs */
  64. #error need to check size allocation for static buffer 'buf'
  65. #endif
  66. extern char *__ultostr(char *buf, unsigned long uval, int base, int uppercase);
  67. char *inet_ntoa(in)
  68. struct in_addr in;
  69. {
  70. static char buf[16]; /* max 12 digits + 3 '.'s + 1 nul */
  71. unsigned long addr = ntohl(in.s_addr);
  72. int i;
  73. char *p, *q;
  74. q = 0;
  75. p = buf + sizeof(buf) - 1;
  76. for (i=0 ; i < 4 ; i++ ) {
  77. p = __ultostr(p, addr & 0xff, 10, 0 ) - 1;
  78. addr >>= 8;
  79. if (q) {
  80. *q = '.';
  81. }
  82. q = p;
  83. }
  84. return p+1;
  85. }
  86. #endif