simple-socket library 1.1.5
|
00001 #include "UnixDatagramSocket.h" 00002 #include "TempFailure.h" 00003 00004 #include <sys/socket.h> 00005 #include <sys/un.h> 00006 #include <poll.h> 00007 00008 using namespace NET; 00009 00010 UnixDatagramSocket::UnixDatagramSocket() 00011 : UnixSocket( DATAGRAM, 0) 00012 {} 00013 00014 void UnixDatagramSocket::sendTo( const void* buffer, size_t len, const std::string& foreignPath) 00015 { 00016 sockaddr_un destAddr; 00017 fillAddress( foreignPath, destAddr); 00018 00019 int sent = TEMP_FAILURE_RETRY (::sendto( m_socket, (const raw_type*)buffer, len, 0, (sockaddr*)&destAddr, sizeof(destAddr))); 00020 00021 // Write out the whole buffer as a single message 00022 if( sent != (int)len) 00023 throw SocketException("Send failed (sendto)"); 00024 } 00025 00026 int UnixDatagramSocket::receiveFrom( void* buffer, size_t len, std::string& sourcePath) 00027 { 00028 sockaddr_un clientAddr; 00029 socklen_t addr_len = sizeof(clientAddr); 00030 00031 int ret = TEMP_FAILURE_RETRY (::recvfrom( m_socket, (raw_type*)buffer, len, 0, (sockaddr*)&clientAddr, &addr_len)); 00032 if( ret < 0) 00033 throw SocketException("Receive failed (recvfrom)"); 00034 00035 sourcePath = extractPath( clientAddr, addr_len); 00036 return ret; 00037 } 00038 00039 int UnixDatagramSocket::timedReceiveFrom( void* buffer, size_t len, std::string& sourcePath, int timeout) 00040 { 00041 struct pollfd poll; 00042 poll.fd = m_socket; 00043 poll.events = POLLIN | POLLPRI | POLLRDHUP; 00044 00045 int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout)); 00046 00047 if( ret == 0) return 0; 00048 if( ret < 0) throw SocketException("Receive failed (poll)"); 00049 00050 if( poll.revents & POLLRDHUP) 00051 m_peerDisconnected = true; 00052 00053 if( poll.revents & POLLIN || poll.revents & POLLPRI) 00054 return receiveFrom( buffer, len, sourcePath); 00055 00056 return 0; 00057 }