NewNet/nntcpserversocket.cpp

00001 /*  NewNet - A networking framework in C++
00002     Copyright (C) 2006 Ingmar K. Steen (iksteen@gmail.com)
00003 
00004     This program is free software; you can redistribute it and/or modify
00005     it under the terms of the GNU General Public License as published by
00006     the Free Software Foundation; either version 2 of the License, or
00007     (at your option) any later version.
00008 
00009     This program is distributed in the hope that it will be useful,
00010     but WITHOUT ANY WARRANTY; without even the implied warranty of
00011     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012     GNU General Public License for more details.
00013 
00014     You should have received a copy of the GNU General Public License
00015     along with this program; if not, write to the Free Software
00016     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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 }

Generated on Sun Jan 7 14:00:01 2007 for NewNet by  doxygen 1.5.1