hmbdc
simplify-high-performance-messaging-programming
 All Classes Namespaces Functions Variables Friends Pages
Endpoint.hpp
1 #pragma once
2 
3 #include "hmbdc/Exception.hpp"
4 
5 #include <string>
6 #include <iostream>
7 #include <stdexcept>
8 
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
11 #include <inttypes.h>
12 #include <string.h>
13 #include <sys/socket.h>
14 
15 namespace hmbdc { namespace comm { namespace inet {
16 struct Endpoint {
17  sockaddr_in v = {0};
18  Endpoint(){}
19  explicit Endpoint(std::string const& ipPort) {
20  char ip[64];
21  uint16_t port;
22  auto s = ipPort;
23  std::replace(std::begin(s), std::end(s), ':', ' ');
24 
25  if (2 != sscanf(s.c_str(), "%s %" SCNu16, ip, &port)) {
26  HMBDC_THROW(std::runtime_error, "incorrect address " << ipPort);
27  }
28  memset(&v, 0, sizeof(v));
29  v.sin_family = AF_INET;
30  v.sin_addr.s_addr = inet_addr(ip);
31  v.sin_port = htons(port);
32  }
33 
34 
35  Endpoint(std::string const& ip, uint16_t port) {
36  memset(&v, 0, sizeof(v));
37  v.sin_family = AF_INET;
38  v.sin_addr.s_addr = inet_addr(ip.c_str());
39  v.sin_port = htons(port);
40  }
41 
42  bool operator == (Endpoint const& other) const {
43  return memcmp(&v, &other.v, sizeof(v)) == 0;
44  }
45  friend
46  std::istream& operator >> (std::istream& is, Endpoint& ep) {
47  std::string ipPort;
48  is >> ipPort
49  ;
50  if (is) {
51  ep = Endpoint(ipPort);
52  }
53  return is;
54  }
55 };
56 }}}
57 
Definition: Endpoint.hpp:16