1 #include "otsdaq/NetworkUtilities/TCPClientBase.h"
5 #include <netinet/in.h>
7 #include <boost/regex.hpp>
14 TCPClientBase::TCPClientBase(
const std::string& serverIP,
int serverPort)
15 : fServerIP(serverIP), fServerPort(serverPort), fConnected(false)
20 TCPClientBase::~TCPClientBase(
void)
22 std::cout << __PRETTY_FUNCTION__ <<
"Closing TCPSocket #" << getSocketId()
26 std::cout << __PRETTY_FUNCTION__ <<
"TCPSocket #" << getSocketId() <<
" closed."
31 bool TCPClientBase::connect(
int retry,
unsigned int sleepMSeconds)
35 std::cout << __PRETTY_FUNCTION__ <<
"I am already connected...what is going on?"
37 throw std::runtime_error(
38 std::string(
"I am already connected...what is going on?"));
42 std::cout << __PRETTY_FUNCTION__ <<
"Connecting Client socket to server name-"
43 << fServerIP <<
"-serverPort: " << fServerPort << std::endl;
44 std::string serverName = fServerIP;
45 resolveServer(fServerIP);
46 std::cout << __PRETTY_FUNCTION__ <<
"Connecting Client socket to server ip -"
47 << fServerIP <<
"-serverPort: " << fServerPort << std::endl;
48 int status = invalidSocketId;
49 struct sockaddr_in serverSocketAddress;
50 serverSocketAddress.sin_family = AF_INET;
51 serverSocketAddress.sin_port = htons(fServerPort);
52 serverSocketAddress.sin_addr.s_addr = inet_addr(fServerIP.c_str());
54 while(!fConnected && (
unsigned int)retry-- > 0)
57 status = ::connect(getSocketId(),
58 (
struct sockaddr*)&serverSocketAddress,
59 sizeof(serverSocketAddress));
63 if((
unsigned int)retry > 0)
65 std::cout << __PRETTY_FUNCTION__ <<
"WARNING: Can't connect to "
66 << serverName <<
". The server might still be down...Sleeping "
67 << sleepMSeconds <<
"ms and then retry " << (
unsigned int)retry
68 <<
" more times." << std::endl;
69 std::this_thread::sleep_for(std::chrono::milliseconds(sleepMSeconds));
74 std::cout << __PRETTY_FUNCTION__ <<
"ERROR: Can't connect to "
75 << serverName <<
" aborting!" << std::endl;
105 std::cout << __PRETTY_FUNCTION__ <<
"Succesfully connected to server "
106 << fServerIP <<
" port: " << fServerPort << std::endl;
115 void TCPClientBase::resolveServer(std::string& serverIP)
117 const std::string ipv4(
118 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
119 "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
120 "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
121 "\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)");
122 boost::regex ip_regex(ipv4.c_str());
125 if(boost::regex_match(serverIP, ip_regex))
127 else if(serverIP ==
"localhost" || serverIP ==
"localhost.localdomain")
129 serverIP =
"127.0.0.1";
133 struct hostent* resolvedHost = ::gethostbyname(serverIP.c_str());
134 if(resolvedHost == NULL)
136 throw std::runtime_error(serverIP +
" is unavailable and can't be resolved!");
139 in_addr* address = (in_addr*)resolvedHost->h_addr;
140 serverIP = inet_ntoa(*address);
141 std::cout <<
"IP: (" << serverIP <<
")\n";