xref: /haiku/src/kits/network/libnetapi/Socket.cpp (revision 25a7b01d15612846f332751841da3579db313082)
1 /*
2  * Copyright 2011, Axel Dörfler, axeld@pinc-software.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <Socket.h>
8 
9 
10 //#define TRACE_SOCKET
11 #ifdef TRACE_SOCKET
12 #	define TRACE(x...) printf(x)
13 #else
14 #	define TRACE(x...) ;
15 #endif
16 
17 
18 BSocket::BSocket()
19 {
20 }
21 
22 
23 BSocket::BSocket(const BNetworkAddress& peer, bigtime_t timeout)
24 {
25 	Connect(peer, timeout);
26 }
27 
28 
29 BSocket::BSocket(const BSocket& other)
30 	:
31 	BAbstractSocket(other)
32 {
33 }
34 
35 
36 BSocket::~BSocket()
37 {
38 }
39 
40 
41 status_t
42 BSocket::Bind(const BNetworkAddress& local)
43 {
44 	return BAbstractSocket::Bind(local, SOCK_STREAM);
45 }
46 
47 
48 status_t
49 BSocket::Connect(const BNetworkAddress& peer, bigtime_t timeout)
50 {
51 	return BAbstractSocket::Connect(peer, SOCK_STREAM, timeout);
52 }
53 
54 
55 //	#pragma mark - BDataIO implementation
56 
57 
58 ssize_t
59 BSocket::Read(void* buffer, size_t size)
60 {
61 	ssize_t bytesReceived = recv(Socket(), buffer, size, 0);
62 	if (bytesReceived < 0) {
63 		TRACE("%p: BSocket::Read() error: %s\n", this, strerror(errno));
64 		return errno;
65 	}
66 
67 	return bytesReceived;
68 }
69 
70 
71 ssize_t
72 BSocket::Write(const void* buffer, size_t size)
73 {
74 	ssize_t bytesSent = send(Socket(), buffer, size, 0);
75 	if (bytesSent < 0) {
76 		TRACE("%p: BSocket::Write() error: %s\n", this, strerror(errno));
77 		return errno;
78 	}
79 
80 	return bytesSent;
81 }
82 
83 
84 //	#pragma mark - private
85 
86 
87 void
88 BSocket::_SetTo(int fd, const BNetworkAddress& local,
89 	const BNetworkAddress& peer)
90 {
91 	Disconnect();
92 
93 	fInitStatus = B_OK;
94 	fSocket = fd;
95 	fLocal = local;
96 	fPeer = peer;
97 
98 	TRACE("%p: accepted from %s to %s\n", this, local.ToString().c_str(),
99 		peer.ToString().c_str());
100 }
101