addr.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. #include <string.h>
  14. #include <ctype.h>
  15. #include <netinet/in.h>
  16. int inet_aton(const char *cp, struct in_addr *inp);
  17. #ifdef L_inet_aton
  18. int inet_aton(cp, inp)
  19. const char *cp;
  20. struct in_addr *inp;
  21. {
  22. unsigned long addr;
  23. int value;
  24. int part;
  25. if (!inp)
  26. return 0;
  27. addr = 0;
  28. for (part = 1; part <= 4; part++) {
  29. if (!isdigit(*cp))
  30. return 0;
  31. value = 0;
  32. while (isdigit(*cp)) {
  33. value *= 10;
  34. value += *cp++ - '0';
  35. if (value > 255)
  36. return 0;
  37. }
  38. if (*cp++ != ((part == 4) ? '\0' : '.'))
  39. return 0;
  40. addr <<= 8;
  41. addr |= value;
  42. }
  43. inp->s_addr = htonl(addr);
  44. return 1;
  45. }
  46. #endif
  47. #ifdef L_inet_addr
  48. unsigned long inet_addr(cp)
  49. const char *cp;
  50. {
  51. struct in_addr a;
  52. if (!inet_aton(cp, &a))
  53. return -1;
  54. else
  55. return a.s_addr;
  56. }
  57. #endif
  58. #ifdef L_inet_ntoa
  59. #include <limits.h>
  60. #if (ULONG_MAX >> 32)
  61. /* We're set up for 32 bit unsigned longs */
  62. #error need to check size allocation for static buffer 'buf'
  63. #endif
  64. extern char *__ultostr(char *buf, unsigned long uval, int base, int uppercase);
  65. char *inet_ntoa(in)
  66. struct in_addr in;
  67. {
  68. static char buf[16]; /* max 12 digits + 3 '.'s + 1 nul */
  69. unsigned long addr = ntohl(in.s_addr);
  70. int i;
  71. char *p, *q;
  72. q = 0;
  73. p = buf + sizeof(buf) - 1;
  74. for (i=0 ; i < 4 ; i++ ) {
  75. p = __ultostr(p, addr & 0xff, 10, 0 ) - 1;
  76. addr >>= 8;
  77. if (q) {
  78. *q = '.';
  79. }
  80. q = p;
  81. }
  82. return p+1;
  83. }
  84. #endif