00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include "nntcpserversocket.h"
00021 #include "nnlog.h"
00022 #include "platform.h"
00023 #include "util.h"
00024 #include <iostream>
00025
00026 void
00027 NewNet::TcpServerSocket::listen(const std::string & host, unsigned int port)
00028 {
00029 struct sockaddr_in address;
00030 memset(&address, 0, sizeof(address));
00031
00032 address.sin_family = AF_INET;
00033 address.sin_port = htons(port);
00034
00035 if(! host.empty())
00036 {
00037 struct hostent *h = gethostbyname(host.c_str());
00038 if (! h)
00039 {
00040 NNLOG("newnet.net.warn", "Cannot resolve '%s'.", host.c_str());
00041 setSocketError(ErrorCannotResolve);
00042 cannotListenEvent(this);
00043 return;
00044 }
00045 memcpy(&(address.sin_addr.s_addr), *(h->h_addr_list), sizeof(address.sin_addr.s_addr));
00046 }
00047 else
00048 address.sin_addr.s_addr = INADDR_ANY;
00049
00050 int sock = socket(PF_INET, SOCK_STREAM, 0);
00051 setnonblocking(sock);
00052
00053 sockopt_t socket_option = 1;
00054 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &socket_option, sizeof(int));
00055
00056 if(bind(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_in)) != 0)
00057 {
00058 NNLOG("newnet.net.warn", "Cannot bind to '%s:%u', error: %i.", host.c_str(), port, errno);
00059 close(sock);
00060 setSocketError(ErrorCannotBind);
00061 cannotListenEvent(this);
00062 return;
00063 }
00064
00065 if (::listen(sock, 3) != 0)
00066 {
00067 NNLOG("newnet.net.warn", "Cannot listen on '%s:%u', error: %i.", host.c_str(), port, errno);
00068 close(sock);
00069 setSocketError(ErrorCannotListen);
00070 cannotListenEvent(this);
00071 return;
00072 }
00073
00074 setDescriptor(sock);
00075 setSocketState(SocketListening);
00076 listeningEvent(this);
00077
00078 NNLOG("newnet.net.debug", "Listening on socket '%s:%u'.", host.c_str(), port);
00079 }