8#include "daq/slc/system/TCPServerSocket.h"
10#include <daq/slc/base/IOException.h>
15#include <sys/socket.h>
19#include <netinet/in.h>
24int TCPServerSocket::open(
const std::string& ip,
unsigned short port,
32int TCPServerSocket::open(
int nqueue)
38 memset(&addr, 0,
sizeof(sockaddr_in));
39 addr.sin_family = AF_INET;
40 addr.sin_addr.s_addr = INADDR_ANY;
41 addr.sin_port = htons(m_port);
43 m_fd = socket(PF_INET, SOCK_STREAM, 0);
46 throw (
IOException(
"Fail to create a server socket."));
49 if (setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(enable)) == -1) {
51 throw (
IOException(
"Fail to set resue address for the socket."));
53 struct hostent* host = NULL;
54 host = gethostbyname(m_ip.c_str());
56 unsigned long ip_address = inet_addr(m_ip.c_str());
57 if ((
signed long) ip_address < 0) {
58 throw (std::exception());
61 host = gethostbyaddr((
char*)&ip_address,
sizeof(ip_address), AF_INET);
65 throw (
IOException(
"Fail to get host ip: %s", m_ip.c_str()));
67 addr.sin_addr.s_addr = (*(
unsigned long*)host->h_addr_list[0]);
69 if (bind(m_fd, (
const sockaddr*) & (addr),
sizeof(sockaddr_in)) != 0) {
70 throw (
IOException(
"Fail to bind the socket. %s:%d", m_ip.c_str(), m_port));
72 if (listen(m_fd, nqueue) != 0) {
73 throw (
IOException(
"Fail to listen to the socket."));
80 socklen_t len =
sizeof(sockaddr_in);
82 memset(&addr, 0,
sizeof(sockaddr_in));
83 addr.sin_family = AF_INET;
84 addr.sin_addr.s_addr = INADDR_ANY;
85 addr.sin_port = htons(m_port);
89 if ((fd = ::accept(m_fd, (sockaddr*) & (addr), &len)) == -1) {
92 case EAGAIN:
continue;
101 s.m_ip = inet_ntoa(addr.sin_addr);
102 s.m_port = ntohs(addr.sin_port);
Abstract base class for different kinds of events.