27 SocketAPM::SocketAPM(
bool _datagram) :
29 socket(AF_INET, _datagram?SOCK_DGRAM:SOCK_STREAM, 0))
32 SocketAPM::SocketAPM(
bool _datagram,
int _fd) :
36 fcntl(fd, F_SETFD, FD_CLOEXEC);
39 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one,
sizeof(one));
43 SocketAPM::~SocketAPM()
51 void SocketAPM::make_sockaddr(
const char *address, uint16_t port,
struct sockaddr_in &sockaddr)
53 memset(&sockaddr, 0,
sizeof(sockaddr));
55 #ifdef HAVE_SOCK_SIN_LEN 56 sockaddr.sin_len =
sizeof(sockaddr);
58 sockaddr.sin_port = htons(port);
59 sockaddr.sin_family = AF_INET;
60 sockaddr.sin_addr.s_addr = inet_addr(address);
66 bool SocketAPM::connect(
const char *address, uint16_t port)
68 struct sockaddr_in sockaddr;
69 make_sockaddr(address, port, sockaddr);
71 if (::connect(fd, (
struct sockaddr *)&sockaddr,
sizeof(sockaddr)) != 0) {
80 bool SocketAPM::bind(
const char *address, uint16_t port)
82 struct sockaddr_in sockaddr;
83 make_sockaddr(address, port, sockaddr);
85 if (::bind(fd, (
struct sockaddr *)&sockaddr,
sizeof(sockaddr)) != 0) {
95 void SocketAPM::reuseaddress(
void)
98 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one,
sizeof(one));
104 void SocketAPM::set_blocking(
bool blocking)
107 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK);
109 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
116 ssize_t SocketAPM::send(
const void *buf,
size_t size)
118 return ::send(fd, buf, size, 0);
124 ssize_t SocketAPM::sendto(
const void *buf,
size_t size,
const char *address, uint16_t port)
126 struct sockaddr_in sockaddr;
127 make_sockaddr(address, port, sockaddr);
128 return ::sendto(fd, buf, size, 0, (
struct sockaddr *)&sockaddr,
sizeof(sockaddr));
134 ssize_t SocketAPM::recv(
void *buf,
size_t size, uint32_t timeout_ms)
136 if (!pollin(timeout_ms)) {
139 socklen_t len =
sizeof(in_addr);
140 return ::recvfrom(fd, buf, size, MSG_DONTWAIT, (sockaddr *)&in_addr, &len);
146 void SocketAPM::last_recv_address(
const char *&ip_addr, uint16_t &port)
148 ip_addr = inet_ntoa(in_addr.sin_addr);
149 port = ntohs(in_addr.sin_port);
152 void SocketAPM::set_broadcast(
void)
155 setsockopt(fd,SOL_SOCKET,SO_BROADCAST,(
char *)&one,
sizeof(one));
161 bool SocketAPM::pollin(uint32_t timeout_ms)
169 tv.tv_sec = timeout_ms / 1000;
170 tv.tv_usec = (timeout_ms % 1000) * 1000UL;
172 if (select(fd+1, &fds,
nullptr,
nullptr, &tv) != 1) {
182 bool SocketAPM::pollout(uint32_t timeout_ms)
190 tv.tv_sec = timeout_ms / 1000;
191 tv.tv_usec = (timeout_ms % 1000) * 1000UL;
193 if (select(fd+1,
nullptr, &fds,
nullptr, &tv) != 1) {
202 bool SocketAPM::listen(uint16_t backlog)
204 return ::listen(fd, (
int)backlog) == 0;
211 SocketAPM *SocketAPM::accept(uint32_t timeout_ms)
213 if (!pollin(timeout_ms)) {
217 int newfd = ::accept(fd,
nullptr,
nullptr);
223 setsockopt(newfd, IPPROTO_TCP, TCP_NODELAY, &one,
sizeof(one));
224 return new SocketAPM(
false, newfd);
227 #endif // HAL_OS_SOCKETS uint16_t size(void) const
int close(int fileno)
POSIX Close a file with fileno handel.