ipv4.c 1.5 KB

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