1 /* 2 * Copyright 2011, Axel Dörfler, axeld@pinc-software.de. 3 * Copyright 2016, Rene Gollent, rene@gollent.com. 4 * Distributed under the terms of the MIT License. 5 */ 6 7 8 #include <Socket.h> 9 10 11 //#define TRACE_SOCKET 12 #ifdef TRACE_SOCKET 13 # define TRACE(x...) printf(x) 14 #else 15 # define TRACE(x...) ; 16 #endif 17 18 19 BSocket::BSocket() 20 { 21 } 22 23 24 BSocket::BSocket(const BNetworkAddress& peer, bigtime_t timeout) 25 { 26 Connect(peer, timeout); 27 } 28 29 30 BSocket::BSocket(const BSocket& other) 31 : 32 BAbstractSocket(other) 33 { 34 } 35 36 37 BSocket::~BSocket() 38 { 39 } 40 41 42 status_t 43 BSocket::Bind(const BNetworkAddress& local, bool reuseAddr) 44 { 45 return BAbstractSocket::Bind(local, SOCK_STREAM, reuseAddr); 46 } 47 48 49 status_t 50 BSocket::Connect(const BNetworkAddress& peer, bigtime_t timeout) 51 { 52 return BAbstractSocket::Connect(peer, SOCK_STREAM, timeout); 53 } 54 55 56 status_t 57 BSocket::Accept(BAbstractSocket*& _socket) 58 { 59 int fd = -1; 60 BNetworkAddress peer; 61 status_t error = AcceptNext(fd, peer); 62 if (error != B_OK) 63 return error; 64 BSocket* socket = new(std::nothrow) BSocket(); 65 if (socket == NULL) { 66 close(fd); 67 return B_NO_MEMORY; 68 } 69 70 socket->_SetTo(fd, fLocal, peer); 71 _socket = socket; 72 return B_OK; 73 } 74 75 76 // #pragma mark - BDataIO implementation 77 78 79 ssize_t 80 BSocket::Read(void* buffer, size_t size) 81 { 82 ssize_t bytesReceived = recv(Socket(), buffer, size, 0); 83 if (bytesReceived < 0) { 84 TRACE("%p: BSocket::Read() error: %s\n", this, strerror(errno)); 85 return errno; 86 } 87 88 return bytesReceived; 89 } 90 91 92 ssize_t 93 BSocket::Write(const void* buffer, size_t size) 94 { 95 ssize_t bytesSent = send(Socket(), buffer, size, 0); 96 if (bytesSent < 0) { 97 TRACE("%p: BSocket::Write() error: %s\n", this, strerror(errno)); 98 return errno; 99 } 100 101 return bytesSent; 102 } 103 104 105 // #pragma mark - private 106 107 108 void 109 BSocket::_SetTo(int fd, const BNetworkAddress& local, 110 const BNetworkAddress& peer) 111 { 112 Disconnect(); 113 114 fInitStatus = B_OK; 115 fSocket = fd; 116 fLocal = local; 117 fPeer = peer; 118 fIsConnected = true; 119 120 TRACE("%p: accepted from %s to %s\n", this, local.ToString().c_str(), 121 peer.ToString().c_str()); 122 } 123