1 #include "daq/slc/system/TCPServerSocket.h"
3 #include <daq/slc/base/IOException.h>
8 #include <sys/socket.h>
12 #include <netinet/in.h>
17 int TCPServerSocket::open(
const std::string& ip,
unsigned short port,
25 int TCPServerSocket::open(
int nqueue)
31 memset(&addr, 0,
sizeof(sockaddr_in));
32 addr.sin_family = AF_INET;
33 addr.sin_addr.s_addr = INADDR_ANY;
34 addr.sin_port = htons(m_port);
36 m_fd = socket(PF_INET, SOCK_STREAM, 0);
39 throw (
IOException(
"Fail to create a server socket."));
42 if (setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(enable)) == -1) {
44 throw (
IOException(
"Fail to set resue address for the socket."));
46 struct hostent* host = NULL;
47 host = gethostbyname(m_ip.c_str());
49 unsigned long ip_address = inet_addr(m_ip.c_str());
50 if ((
signed long) ip_address < 0) {
51 throw (std::exception());
54 host = gethostbyaddr((
char*)&ip_address,
sizeof(ip_address), AF_INET);
58 throw (
IOException(
"Fail to get host ip: %s", m_ip.c_str()));
60 addr.sin_addr.s_addr = (*(
unsigned long*)host->h_addr_list[0]);
62 if (bind(m_fd, (
const sockaddr*) & (addr),
sizeof(sockaddr_in)) != 0) {
63 throw (
IOException(
"Fail to bind the socket. %s:%d", m_ip.c_str(), m_port));
65 if (listen(m_fd, nqueue) != 0) {
66 throw (
IOException(
"Fail to listen to the socket."));
73 socklen_t len =
sizeof(sockaddr_in);
75 memset(&addr, 0,
sizeof(sockaddr_in));
76 addr.sin_family = AF_INET;
77 addr.sin_addr.s_addr = INADDR_ANY;
78 addr.sin_port = htons(m_port);
82 if ((fd = ::accept(m_fd, (sockaddr*) & (addr), &len)) == -1) {
85 case EAGAIN:
continue;
94 s.m_ip = inet_ntoa(addr.sin_addr);
95 s.m_port = ntohs(addr.sin_port);