simple-socket library 1.1.5

UnixSocket.cpp

Go to the documentation of this file.
00001 #include "UnixSocket.h"
00002 
00003 #include <sys/socket.h>
00004 #include <sys/un.h>
00005 #include <cstring>
00006 
00007 using namespace NET;
00008 
00009 UnixSocket::UnixSocket( int type, int protocol)
00010 : SimpleSocket( UNIX, type, protocol)
00011 {}
00012 
00013 void UnixSocket::connect( const std::string& foreignPath)
00014 {
00015     sockaddr_un addr;
00016     fillAddress( foreignPath, addr);
00017 
00018     if( ::connect( m_socket, (sockaddr*) &addr, sizeof(addr)) < 0)
00019         throw SocketException("Connect failed (connect)");
00020 }
00021 
00022 void UnixSocket::bind( const std::string& localPath)
00023 {
00024     sockaddr_un addr;
00025     fillAddress( localPath, addr);
00026     ::unlink( addr.sun_path);
00027 
00028     if( ::bind( m_socket, (sockaddr*) &addr, sizeof(addr)) < 0)
00029         throw SocketException("Set of local path failed (bind)");
00030 }
00031 
00032 std::string UnixSocket::getLocalPath() const
00033 {
00034     sockaddr_un addr;
00035     socklen_t addr_len = sizeof(addr);
00036 
00037     if( getsockname( m_socket, (sockaddr*) &addr, &addr_len) < 0)
00038         throw SocketException("Fetch of local path failed (getsockname)");
00039 
00040     return extractPath( addr, addr_len);
00041 }
00042 
00043 std::string UnixSocket::getForeignPath() const
00044 {
00045     sockaddr_un addr;
00046     socklen_t addr_len = sizeof(addr);
00047 
00048     if( getpeername( m_socket, (sockaddr*) &addr, &addr_len) < 0)
00049         throw SocketException("Fetch of foreign path failed (getpeername)");
00050 
00051     return extractPath( addr, addr_len);
00052 }
00053 
00054 void UnixSocket::fillAddress( const std::string& path, sockaddr_un& addr)
00055 {
00056     // needed space is size plus null character
00057     if( path.size() >= sizeof(sockaddr_un::sun_path))
00058         throw SocketException("Path to socket file is too long", false);
00059 
00060     addr.sun_family = AF_LOCAL;
00061     std::strcpy( addr.sun_path, path.c_str());
00062 }
00063 
00064 std::string UnixSocket::extractPath( const sockaddr_un& addr, socklen_t len)
00065 {
00066     return std::string( addr.sun_path, len - sizeof(sa_family_t) - 1);
00067 }