33 #include <netinet/in.h>
34 #include <netinet/tcp.h>
35 #include <sys/socket.h>
36 #include <sys/types.h>
56 panic(
"Too late to disable all listeners, already have a listener");
57 listeningDisabled =
true;
63 return listeningDisabled;
70 panic(
"Too late to bind to loopback, already have a listener");
71 bindToLoopback =
true;
79 : listening(false),
fd(-1)
93 panic(
"Socket already listening!");
95 fd = ::socket(PF_INET, SOCK_STREAM, 0);
97 panic(
"Can't create socket:%s !", strerror(errno));
101 if (::setsockopt(
fd, SOL_SOCKET, SO_REUSEADDR, (
char *)&i,
103 panic(
"ListenSocket(listen): setsockopt() SO_REUSEADDR failed!");
106 struct sockaddr_in sockaddr;
107 sockaddr.sin_family = PF_INET;
108 sockaddr.sin_addr.s_addr =
109 htobe<unsigned long>(
bindToLoopback ? INADDR_LOOPBACK : INADDR_ANY);
110 sockaddr.sin_port = htons(port);
112 memset(&sockaddr.sin_zero, 0,
sizeof(sockaddr.sin_zero));
113 int ret = ::bind(
fd, (
struct sockaddr *)&sockaddr,
sizeof (sockaddr));
115 if (ret == -1 && errno != EADDRINUSE)
116 panic(
"ListenSocket(listen): bind() failed!");
121 if (errno != EADDRINUSE)
122 panic(
"ListenSocket(listen): listen() failed!");
138 struct sockaddr_in sockaddr;
139 socklen_t slen =
sizeof (sockaddr);
140 int sfd =
::accept(
fd, (
struct sockaddr *)&sockaddr, &slen);
141 if (sfd != -1 && nodelay) {
143 if (::setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (
char *)&i,
145 warn(
"ListenSocket(accept): setsockopt() TCP_NODELAY failed!");
virtual bool listen(int port, bool reuse=true)
static bool bindToLoopback
static bool allDisabled()
static void loopbackOnly()
virtual int accept(bool nodelay=false)
Defines global host-dependent types: Counter, Tick, and (indirectly) {int,uint}{8,16,32,64}_t.
static bool listeningDisabled