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