sockaddr.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 <exceptions/exceptions.h>
  20. namespace isc {
  21. namespace acl {
  22. namespace tests {
  23. // This is a helper function that returns a sockaddr for the given textual
  24. // IP address. Note that "inline" is crucial because this function is defined
  25. // in a header file included in multiple .cc files. Without inline it would
  26. // produce an external linkage and cause troubles at link time.
  27. //
  28. // Note that this function uses a static storage for the return value.
  29. // So if it's called more than once in a singe context (e.g., in the same
  30. // EXPECT_xx()), it's unlikely to work as expected.
  31. inline const struct sockaddr&
  32. getSockAddr(const char* const addr) {
  33. struct addrinfo hints, *res;
  34. memset(&hints, 0, sizeof(hints));
  35. hints.ai_family = AF_UNSPEC;
  36. hints.ai_socktype = SOCK_STREAM;
  37. hints.ai_flags = AI_NUMERICHOST;
  38. if (getaddrinfo(addr, NULL, &hints, &res) == 0) {
  39. static struct sockaddr_storage ss;
  40. void* ss_ptr = &ss;
  41. memcpy(ss_ptr, res->ai_addr, res->ai_addrlen);
  42. freeaddrinfo(res);
  43. return (*static_cast<struct sockaddr*>(ss_ptr));
  44. }
  45. // We don't expect getaddrinfo to fail for our tests. But if that
  46. // ever happens we throw an exception to make sure the corresponding test
  47. // fail (either due to a failure of *_NO_THROW or the uncaught exception).
  48. isc_throw(Unexpected,
  49. "failed to convert textual IP address to sockaddr for " <<
  50. addr);
  51. }
  52. } // end of namespace "tests"
  53. } // end of namespace "acl"
  54. } // end of namespace "isc"
  55. #endif // __ACL_TEST_SOCKADDR_H
  56. // Local Variables:
  57. // mode: c++
  58. // End: