sockaddr.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef ACL_TEST_SOCKADDR_H
  15. #define ACL_TEST_SOCKADDR_H 1
  16. #include <sys/types.h>
  17. #include <sys/socket.h>
  18. #include <netdb.h>
  19. #include <string.h>
  20. #include <exceptions/exceptions.h>
  21. namespace isc {
  22. namespace acl {
  23. namespace tests {
  24. // This is a helper function that returns a sockaddr for the given textual
  25. // IP address. Note that "inline" is crucial because this function is defined
  26. // in a header file included in multiple .cc files. Without inline it would
  27. // produce an external linkage and cause troubles at link time.
  28. //
  29. // Note that this function uses a static storage for the return value.
  30. // So if it's called more than once in a singe context (e.g., in the same
  31. // EXPECT_xx()), it's unlikely to work as expected.
  32. inline const struct sockaddr&
  33. getSockAddr(const char* const addr) {
  34. struct addrinfo hints, *res;
  35. memset(&hints, 0, sizeof(hints));
  36. hints.ai_family = AF_UNSPEC;
  37. hints.ai_socktype = SOCK_STREAM;
  38. hints.ai_flags = AI_NUMERICHOST;
  39. if (getaddrinfo(addr, NULL, &hints, &res) == 0) {
  40. static struct sockaddr_storage ss;
  41. void* ss_ptr = &ss;
  42. memcpy(ss_ptr, res->ai_addr, res->ai_addrlen);
  43. freeaddrinfo(res);
  44. return (*static_cast<struct sockaddr*>(ss_ptr));
  45. }
  46. // We don't expect getaddrinfo to fail for our tests. But if that
  47. // ever happens we throw an exception to make sure the corresponding test
  48. // fail (either due to a failure of *_NO_THROW or the uncaught exception).
  49. isc_throw(Unexpected,
  50. "failed to convert textual IP address to sockaddr for " <<
  51. addr);
  52. }
  53. } // end of namespace "tests"
  54. } // end of namespace "acl"
  55. } // end of namespace "isc"
  56. #endif // ACL_TEST_SOCKADDR_H
  57. // Local Variables:
  58. // mode: c++
  59. // End: