GComm  0.2.3
asio_addr.hpp
1 /*
2  * Copyright (C) 2010 Codership Oy <info@codership.com>
3  */
4 
5 #ifndef GCOMM_ASIO_ADDR_HPP
6 #define GCOMM_ASIO_ADDR_HPP
7 
8 #include "gu_exception.hpp"
9 
10 #include "asio_protonet.hpp"
11 
12 #include <string>
13 #include <algorithm>
14 
15 namespace gcomm
16 {
17  static inline std::string escape_addr(const asio::ip::address& addr)
18  {
19  if (addr.is_v4())
20  {
21  return addr.to_v4().to_string();
22  }
23  else
24  {
25  return "[" + addr.to_v6().to_string() + "]";
26  }
27  }
28 
29  static inline std::string unescape_addr(const std::string& addr)
30  {
31  std::string ret(addr);
32  size_t pos(ret.find('['));
33  if (pos != std::string::npos) ret.erase(pos, 1);
34  pos = ret.find(']');
35  if (pos != std::string::npos) ret.erase(pos, 1);
36  return ret;
37  }
38 
39 
40  static inline std::string anyaddr(const asio::ip::address& addr)
41  {
42  if (addr.is_v4() == true)
43  {
44  return addr.to_v4().any().to_string();
45  }
46  else
47  {
48  return addr.to_v6().any().to_string();
49  }
50  gu_throw_fatal;
51  }
52 }
53 
54 template <class S>
55 void set_fd_options(S& socket)
56 {
57  long flags(FD_CLOEXEC);
58  if (fcntl(socket.native(), F_SETFD, flags) == -1)
59  {
60  gu_throw_error(errno) << "failed to set FD_CLOEXEC";
61  }
62 }
63 
64 
65 #endif // GCOMM_ASIO_ADDR_HPP