NewNet/nnunixclientsocket.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 "nnunixclientsocket.h"
00021 #include "nnlog.h"
00022 #include "platform.h"
00023 #include <iostream>
00024 
00025 void
00026 NewNet::UnixClientSocket::connect(const std::string & path)
00027 {
00028   // FIXME: Make the UnixClientSocket class a bit more functional
00029   assert((descriptor() == -1) || (socketState() == SocketUninitialized));
00030 
00031   setSocketState(SocketConnecting);
00032 
00033   if(path.length() >= UNIX_PATH_MAX)
00034   {
00035     NNLOG("newnet.net.warn", "Unix socket path too long: '%s'.", path.c_str());
00036     setSocketError(ErrorInvalidPath);
00037     cannotConnectEvent(this);
00038     return;
00039   }
00040 
00041   struct sockaddr_un address;
00042   memset(&address, 0, sizeof(address));
00043   address.sun_family = AF_UNIX;
00044   memcpy(address.sun_path, path.c_str(), path.length()+1);
00045 
00046   NNLOG("newnet.net.debug", "Connecting to unix socket '%s'.", path.c_str());
00047 
00048   int sock = socket(PF_UNIX, SOCK_STREAM, 0);
00049   fcntl(sock, F_SETFL, O_NONBLOCK);
00050   setDescriptor(sock);
00051 
00052   if(::connect(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_un)) == 0)
00053   {
00054     NNLOG("newnet.net.debug", "Connected to unix socket '%s'.", path.c_str());
00055     setDescriptor(sock);
00056     setSocketState(SocketConnected);
00057     connectedEvent(this);
00058     return;
00059   }
00060   else if(errno != EINPROGRESS)
00061   {
00062     NNLOG("newnet.net.warn", "Cannot connect to unix socket '%s', error: %i.", path.c_str(), errno);
00063     close(sock);
00064     setSocketError(ErrorCannotConnect);
00065     cannotConnectEvent(this);
00066     return;
00067   }
00068   setDescriptor(sock);
00069 }

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