ipv4.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file ipv4.c
  7. * \brief Functions for encoding and decoding IPv4 addresses into strings
  8. **/
  9. #include "orconfig.h"
  10. #include "lib/cc/torint.h"
  11. #include "lib/net/ipv4.h"
  12. #include "lib/string/printf.h"
  13. #include "lib/string/scanf.h"
  14. #ifdef HAVE_ARPA_INET_H
  15. #include <arpa/inet.h>
  16. #endif
  17. #ifdef _WIN32
  18. #include <winsock2.h>
  19. #endif
  20. /** Set *addr to the IP address (in dotted-quad notation) stored in *str.
  21. * Return 1 on success, 0 if *str is badly formatted.
  22. * (Like inet_aton(str,addr), but works on Windows and Solaris.)
  23. */
  24. int
  25. tor_inet_aton(const char *str, struct in_addr* addr)
  26. {
  27. unsigned a,b,c,d;
  28. char more;
  29. if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4)
  30. return 0;
  31. if (a > 255) return 0;
  32. if (b > 255) return 0;
  33. if (c > 255) return 0;
  34. if (d > 255) return 0;
  35. addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
  36. return 1;
  37. }
  38. /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
  39. * write it as a string into the <b>buf_len</b>-byte buffer in
  40. * <b>buf</b>. Returns a non-negative integer on success.
  41. * Returns -1 on failure.
  42. */
  43. int
  44. tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
  45. {
  46. uint32_t a = ntohl(in->s_addr);
  47. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  48. (int)(uint8_t)((a>>24)&0xff),
  49. (int)(uint8_t)((a>>16)&0xff),
  50. (int)(uint8_t)((a>>8 )&0xff),
  51. (int)(uint8_t)((a )&0xff));
  52. }