34 #include <netinet/in.h>
35 #include <netinet/tcp.h>
36 #include <sys/socket.h>
37 #include <sys/types.h>
56 listeningDisabled =
false;
58 bindToLoopback =
false;
65 panic(
"Too late to disable all listeners, already have a listener");
66 listeningDisabled =
true;
72 return listeningDisabled;
79 panic(
"Too late to bind to loopback, already have a listener");
80 bindToLoopback =
true;
88 : listening(false),
fd(-1)
102 panic(
"Socket already listening!");
106 fd = ::socket(PF_INET, SOCK_STREAM, 0);
108 panic(
"Can't create socket:%s !", strerror(errno));
113 if (::setsockopt(
fd, SOL_SOCKET, SO_REUSEADDR, (
char *)&
i,
115 panic(
"ListenSocket(listen): setsockopt() SO_REUSEADDR failed!");
118 struct sockaddr_in sockaddr;
119 sockaddr.sin_family = PF_INET;
120 sockaddr.sin_addr.s_addr =
122 sockaddr.sin_port = htons(port);
124 memset(&sockaddr.sin_zero, 0,
sizeof(sockaddr.sin_zero));
125 int ret = ::bind(
fd, (
struct sockaddr *)&sockaddr,
sizeof (sockaddr));
127 if (ret == -1 && errno != EADDRINUSE)
128 panic(
"ListenSocket(listen): bind() failed!");
133 if (errno != EADDRINUSE)
134 panic(
"ListenSocket(listen): listen() failed!");
150 struct sockaddr_in sockaddr;
151 socklen_t slen =
sizeof (sockaddr);
152 int sfd =
::accept(
fd, (
struct sockaddr *)&sockaddr, &slen);
153 if (sfd != -1 && nodelay) {
155 if (::setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (
char *)&
i,
157 warn(
"ListenSocket(accept): setsockopt() TCP_NODELAY failed!");