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