2 // detail/impl/socket_ops.ipp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
11 #ifndef BOOST_ASIO_DETAIL_SOCKET_OPS_IPP
12 #define BOOST_ASIO_DETAIL_SOCKET_OPS_IPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/config.hpp>
26 #include <boost/asio/detail/assert.hpp>
27 #include <boost/asio/detail/socket_ops.hpp>
28 #include <boost/asio/error.hpp>
30 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
34 #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
36 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__) \
37 || defined(__MACH__) && defined(__APPLE__)
38 # if defined(BOOST_ASIO_HAS_PTHREADS)
40 # endif // defined(BOOST_ASIO_HAS_PTHREADS)
41 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
42 // || defined(__MACH__) && defined(__APPLE__)
44 #include <boost/asio/detail/push_options.hpp>
49 namespace socket_ops {
51 #if !defined(BOOST_ASIO_WINDOWS_RUNTIME)
53 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
54 struct msghdr { int msg_namelen; };
55 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
58 // HP-UX doesn't declare these functions extern "C", so they are declared again
59 // here to avoid linker errors about undefined symbols.
60 extern "C" char* if_indextoname(unsigned int, char*);
61 extern "C" unsigned int if_nametoindex(const char*);
62 #endif // defined(__hpux)
64 #endif // !defined(BOOST_ASIO_WINDOWS_RUNTIME)
66 inline void clear_last_error()
68 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
75 #if !defined(BOOST_ASIO_WINDOWS_RUNTIME)
77 inline void get_last_error(
78 boost::system::error_code& ec, bool is_error_condition)
80 if (!is_error_condition)
82 ec.assign(0, ec.category());
86 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
87 ec = boost::system::error_code(WSAGetLastError(),
88 boost::asio::error::get_system_category());
90 ec = boost::system::error_code(errno,
91 boost::asio::error::get_system_category());
96 template <typename SockLenType>
97 inline socket_type call_accept(SockLenType msghdr::*,
98 socket_type s, socket_addr_type* addr, std::size_t* addrlen)
100 SockLenType tmp_addrlen = addrlen ? (SockLenType)*addrlen : 0;
101 socket_type result = ::accept(s, addr, addrlen ? &tmp_addrlen : 0);
103 *addrlen = (std::size_t)tmp_addrlen;
107 socket_type accept(socket_type s, socket_addr_type* addr,
108 std::size_t* addrlen, boost::system::error_code& ec)
110 if (s == invalid_socket)
112 ec = boost::asio::error::bad_descriptor;
113 return invalid_socket;
116 socket_type new_s = call_accept(&msghdr::msg_namelen, s, addr, addrlen);
117 get_last_error(ec, new_s == invalid_socket);
118 if (new_s == invalid_socket)
121 #if defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
123 int result = ::setsockopt(new_s, SOL_SOCKET,
124 SO_NOSIGPIPE, &optval, sizeof(optval));
125 get_last_error(ec, result != 0);
129 return invalid_socket;
133 ec.assign(0, ec.category());
137 socket_type sync_accept(socket_type s, state_type state,
138 socket_addr_type* addr, std::size_t* addrlen, boost::system::error_code& ec)
143 // Try to complete the operation without blocking.
144 socket_type new_socket = socket_ops::accept(s, addr, addrlen, ec);
146 // Check if operation succeeded.
147 if (new_socket != invalid_socket)
151 if (ec == boost::asio::error::would_block
152 || ec == boost::asio::error::try_again)
154 if (state & user_set_non_blocking)
155 return invalid_socket;
156 // Fall through to retry operation.
158 else if (ec == boost::asio::error::connection_aborted)
160 if (state & enable_connection_aborted)
161 return invalid_socket;
162 // Fall through to retry operation.
165 else if (ec.value() == EPROTO)
167 if (state & enable_connection_aborted)
168 return invalid_socket;
169 // Fall through to retry operation.
171 #endif // defined(EPROTO)
173 return invalid_socket;
175 // Wait for socket to become ready.
176 if (socket_ops::poll_read(s, 0, -1, ec) < 0)
177 return invalid_socket;
181 #if defined(BOOST_ASIO_HAS_IOCP)
183 void complete_iocp_accept(socket_type s,
184 void* output_buffer, DWORD address_length,
185 socket_addr_type* addr, std::size_t* addrlen,
186 socket_type new_socket, boost::system::error_code& ec)
188 // Map non-portable errors to their portable counterparts.
189 if (ec.value() == ERROR_NETNAME_DELETED)
190 ec = boost::asio::error::connection_aborted;
194 // Get the address of the peer.
197 LPSOCKADDR local_addr = 0;
198 int local_addr_length = 0;
199 LPSOCKADDR remote_addr = 0;
200 int remote_addr_length = 0;
201 GetAcceptExSockaddrs(output_buffer, 0, address_length,
202 address_length, &local_addr, &local_addr_length,
203 &remote_addr, &remote_addr_length);
204 if (static_cast<std::size_t>(remote_addr_length) > *addrlen)
206 ec = boost::asio::error::invalid_argument;
210 using namespace std; // For memcpy.
211 memcpy(addr, remote_addr, remote_addr_length);
212 *addrlen = static_cast<std::size_t>(remote_addr_length);
216 // Need to set the SO_UPDATE_ACCEPT_CONTEXT option so that getsockname
217 // and getpeername will work on the accepted socket.
218 SOCKET update_ctx_param = s;
219 socket_ops::state_type state = 0;
220 socket_ops::setsockopt(new_socket, state,
221 SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
222 &update_ctx_param, sizeof(SOCKET), ec);
226 #else // defined(BOOST_ASIO_HAS_IOCP)
228 bool non_blocking_accept(socket_type s,
229 state_type state, socket_addr_type* addr, std::size_t* addrlen,
230 boost::system::error_code& ec, socket_type& new_socket)
234 // Accept the waiting connection.
235 new_socket = socket_ops::accept(s, addr, addrlen, ec);
237 // Check if operation succeeded.
238 if (new_socket != invalid_socket)
241 // Retry operation if interrupted by signal.
242 if (ec == boost::asio::error::interrupted)
246 if (ec == boost::asio::error::would_block
247 || ec == boost::asio::error::try_again)
249 // Fall through to retry operation.
251 else if (ec == boost::asio::error::connection_aborted)
253 if (state & enable_connection_aborted)
255 // Fall through to retry operation.
258 else if (ec.value() == EPROTO)
260 if (state & enable_connection_aborted)
262 // Fall through to retry operation.
264 #endif // defined(EPROTO)
272 #endif // defined(BOOST_ASIO_HAS_IOCP)
274 template <typename SockLenType>
275 inline int call_bind(SockLenType msghdr::*,
276 socket_type s, const socket_addr_type* addr, std::size_t addrlen)
278 return ::bind(s, addr, (SockLenType)addrlen);
281 int bind(socket_type s, const socket_addr_type* addr,
282 std::size_t addrlen, boost::system::error_code& ec)
284 if (s == invalid_socket)
286 ec = boost::asio::error::bad_descriptor;
287 return socket_error_retval;
290 int result = call_bind(&msghdr::msg_namelen, s, addr, addrlen);
291 get_last_error(ec, result != 0);
295 int close(socket_type s, state_type& state,
296 bool destruction, boost::system::error_code& ec)
299 if (s != invalid_socket)
301 // We don't want the destructor to block, so set the socket to linger in
302 // the background. If the user doesn't like this behaviour then they need
303 // to explicitly close the socket.
304 if (destruction && (state & user_set_linger))
309 boost::system::error_code ignored_ec;
310 socket_ops::setsockopt(s, state, SOL_SOCKET,
311 SO_LINGER, &opt, sizeof(opt), ignored_ec);
314 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
315 result = ::closesocket(s);
316 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
318 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
319 get_last_error(ec, result != 0);
322 && (ec == boost::asio::error::would_block
323 || ec == boost::asio::error::try_again))
325 // According to UNIX Network Programming Vol. 1, it is possible for
326 // close() to fail with EWOULDBLOCK under certain circumstances. What
327 // isn't clear is the state of the descriptor after this error. The one
328 // current OS where this behaviour is seen, Windows, says that the socket
329 // remains open. Therefore we'll put the descriptor back into blocking
330 // mode and have another attempt at closing it.
331 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
332 ioctl_arg_type arg = 0;
333 ::ioctlsocket(s, FIONBIO, &arg);
334 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
335 # if defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
336 int flags = ::fcntl(s, F_GETFL, 0);
338 ::fcntl(s, F_SETFL, flags & ~O_NONBLOCK);
339 # else // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
340 ioctl_arg_type arg = 0;
341 ::ioctl(s, FIONBIO, &arg);
342 # endif // defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
343 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
344 state &= ~non_blocking;
346 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
347 result = ::closesocket(s);
348 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
350 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
351 get_last_error(ec, result != 0);
358 bool set_user_non_blocking(socket_type s,
359 state_type& state, bool value, boost::system::error_code& ec)
361 if (s == invalid_socket)
363 ec = boost::asio::error::bad_descriptor;
367 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
368 ioctl_arg_type arg = (value ? 1 : 0);
369 int result = ::ioctlsocket(s, FIONBIO, &arg);
370 get_last_error(ec, result < 0);
371 #elif defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
372 int result = ::fcntl(s, F_GETFL, 0);
373 get_last_error(ec, result < 0);
376 int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
377 result = ::fcntl(s, F_SETFL, flag);
378 get_last_error(ec, result < 0);
381 ioctl_arg_type arg = (value ? 1 : 0);
382 int result = ::ioctl(s, FIONBIO, &arg);
383 get_last_error(ec, result < 0);
389 state |= user_set_non_blocking;
392 // Clearing the user-set non-blocking mode always overrides any
393 // internally-set non-blocking flag. Any subsequent asynchronous
394 // operations will need to re-enable non-blocking I/O.
395 state &= ~(user_set_non_blocking | internal_non_blocking);
403 bool set_internal_non_blocking(socket_type s,
404 state_type& state, bool value, boost::system::error_code& ec)
406 if (s == invalid_socket)
408 ec = boost::asio::error::bad_descriptor;
412 if (!value && (state & user_set_non_blocking))
414 // It does not make sense to clear the internal non-blocking flag if the
415 // user still wants non-blocking behaviour. Return an error and let the
416 // caller figure out whether to update the user-set non-blocking flag.
417 ec = boost::asio::error::invalid_argument;
421 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
422 ioctl_arg_type arg = (value ? 1 : 0);
423 int result = ::ioctlsocket(s, FIONBIO, &arg);
424 get_last_error(ec, result < 0);
425 #elif defined(__SYMBIAN32__) || defined(__EMSCRIPTEN__)
426 int result = ::fcntl(s, F_GETFL, 0);
427 get_last_error(ec, result < 0);
430 int flag = (value ? (result | O_NONBLOCK) : (result & ~O_NONBLOCK));
431 result = ::fcntl(s, F_SETFL, flag);
432 get_last_error(ec, result < 0);
435 ioctl_arg_type arg = (value ? 1 : 0);
436 int result = ::ioctl(s, FIONBIO, &arg);
437 get_last_error(ec, result < 0);
443 state |= internal_non_blocking;
445 state &= ~internal_non_blocking;
452 int shutdown(socket_type s, int what, boost::system::error_code& ec)
454 if (s == invalid_socket)
456 ec = boost::asio::error::bad_descriptor;
457 return socket_error_retval;
460 int result = ::shutdown(s, what);
461 get_last_error(ec, result != 0);
465 template <typename SockLenType>
466 inline int call_connect(SockLenType msghdr::*,
467 socket_type s, const socket_addr_type* addr, std::size_t addrlen)
469 return ::connect(s, addr, (SockLenType)addrlen);
472 int connect(socket_type s, const socket_addr_type* addr,
473 std::size_t addrlen, boost::system::error_code& ec)
475 if (s == invalid_socket)
477 ec = boost::asio::error::bad_descriptor;
478 return socket_error_retval;
481 int result = call_connect(&msghdr::msg_namelen, s, addr, addrlen);
482 get_last_error(ec, result != 0);
483 #if defined(__linux__)
484 if (result != 0 && ec == boost::asio::error::try_again)
485 ec = boost::asio::error::no_buffer_space;
486 #endif // defined(__linux__)
490 void sync_connect(socket_type s, const socket_addr_type* addr,
491 std::size_t addrlen, boost::system::error_code& ec)
493 // Perform the connect operation.
494 socket_ops::connect(s, addr, addrlen, ec);
495 if (ec != boost::asio::error::in_progress
496 && ec != boost::asio::error::would_block)
498 // The connect operation finished immediately.
502 // Wait for socket to become ready.
503 if (socket_ops::poll_connect(s, -1, ec) < 0)
506 // Get the error code from the connect operation.
507 int connect_error = 0;
508 size_t connect_error_len = sizeof(connect_error);
509 if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_ERROR,
510 &connect_error, &connect_error_len, ec) == socket_error_retval)
513 // Return the result of the connect operation.
514 ec = boost::system::error_code(connect_error,
515 boost::asio::error::get_system_category());
518 #if defined(BOOST_ASIO_HAS_IOCP)
520 void complete_iocp_connect(socket_type s, boost::system::error_code& ec)
522 // Map non-portable errors to their portable counterparts.
525 case ERROR_CONNECTION_REFUSED:
526 ec = boost::asio::error::connection_refused;
528 case ERROR_NETWORK_UNREACHABLE:
529 ec = boost::asio::error::network_unreachable;
531 case ERROR_HOST_UNREACHABLE:
532 ec = boost::asio::error::host_unreachable;
534 case ERROR_SEM_TIMEOUT:
535 ec = boost::asio::error::timed_out;
543 // Need to set the SO_UPDATE_CONNECT_CONTEXT option so that getsockname
544 // and getpeername will work on the connected socket.
545 socket_ops::state_type state = 0;
546 const int so_update_connect_context = 0x7010;
547 socket_ops::setsockopt(s, state, SOL_SOCKET,
548 so_update_connect_context, 0, 0, ec);
552 #endif // defined(BOOST_ASIO_HAS_IOCP)
554 bool non_blocking_connect(socket_type s, boost::system::error_code& ec)
556 // Check if the connect operation has finished. This is required since we may
557 // get spurious readiness notifications from the reactor.
558 #if defined(BOOST_ASIO_WINDOWS) \
559 || defined(__CYGWIN__) \
560 || defined(__SYMBIAN32__)
563 FD_SET(s, &write_fds);
565 FD_ZERO(&except_fds);
566 FD_SET(s, &except_fds);
567 timeval zero_timeout;
568 zero_timeout.tv_sec = 0;
569 zero_timeout.tv_usec = 0;
570 int ready = ::select(s + 1, 0, &write_fds, &except_fds, &zero_timeout);
571 #else // defined(BOOST_ASIO_WINDOWS)
572 // || defined(__CYGWIN__)
573 // || defined(__SYMBIAN32__)
576 fds.events = POLLOUT;
578 int ready = ::poll(&fds, 1, 0);
579 #endif // defined(BOOST_ASIO_WINDOWS)
580 // || defined(__CYGWIN__)
581 // || defined(__SYMBIAN32__)
584 // The asynchronous connect operation is still in progress.
588 // Get the error code from the connect operation.
589 int connect_error = 0;
590 size_t connect_error_len = sizeof(connect_error);
591 if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_ERROR,
592 &connect_error, &connect_error_len, ec) == 0)
596 ec = boost::system::error_code(connect_error,
597 boost::asio::error::get_system_category());
600 ec.assign(0, ec.category());
606 int socketpair(int af, int type, int protocol,
607 socket_type sv[2], boost::system::error_code& ec)
609 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
614 ec = boost::asio::error::operation_not_supported;
615 return socket_error_retval;
617 int result = ::socketpair(af, type, protocol, sv);
618 get_last_error(ec, result != 0);
623 bool sockatmark(socket_type s, boost::system::error_code& ec)
625 if (s == invalid_socket)
627 ec = boost::asio::error::bad_descriptor;
631 #if defined(SIOCATMARK)
632 ioctl_arg_type value = 0;
633 # if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
634 int result = ::ioctlsocket(s, SIOCATMARK, &value);
635 # else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
636 int result = ::ioctl(s, SIOCATMARK, &value);
637 # endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
638 get_last_error(ec, result < 0);
640 if (ec.value() == ENOTTY)
641 ec = boost::asio::error::not_socket;
642 # endif // defined(ENOTTY)
643 #else // defined(SIOCATMARK)
644 int value = ::sockatmark(s);
645 get_last_error(ec, result < 0);
646 #endif // defined(SIOCATMARK)
648 return ec ? false : value != 0;
651 size_t available(socket_type s, boost::system::error_code& ec)
653 if (s == invalid_socket)
655 ec = boost::asio::error::bad_descriptor;
659 ioctl_arg_type value = 0;
660 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
661 int result = ::ioctlsocket(s, FIONREAD, &value);
662 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
663 int result = ::ioctl(s, FIONREAD, &value);
664 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
665 get_last_error(ec, result < 0);
667 if (ec.value() == ENOTTY)
668 ec = boost::asio::error::not_socket;
669 #endif // defined(ENOTTY)
671 return ec ? static_cast<size_t>(0) : static_cast<size_t>(value);
674 int listen(socket_type s, int backlog, boost::system::error_code& ec)
676 if (s == invalid_socket)
678 ec = boost::asio::error::bad_descriptor;
679 return socket_error_retval;
682 int result = ::listen(s, backlog);
683 get_last_error(ec, result != 0);
687 inline void init_buf_iov_base(void*& base, void* addr)
692 template <typename T>
693 inline void init_buf_iov_base(T& base, void* addr)
695 base = static_cast<T>(addr);
698 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
700 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
702 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
704 void init_buf(buf& b, void* data, size_t size)
706 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
707 b.buf = static_cast<char*>(data);
708 b.len = static_cast<u_long>(size);
709 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
710 init_buf_iov_base(b.iov_base, data);
712 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
715 void init_buf(buf& b, const void* data, size_t size)
717 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
718 b.buf = static_cast<char*>(const_cast<void*>(data));
719 b.len = static_cast<u_long>(size);
720 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
721 init_buf_iov_base(b.iov_base, const_cast<void*>(data));
723 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
726 inline void init_msghdr_msg_name(void*& name, socket_addr_type* addr)
731 inline void init_msghdr_msg_name(void*& name, const socket_addr_type* addr)
733 name = const_cast<socket_addr_type*>(addr);
736 template <typename T>
737 inline void init_msghdr_msg_name(T& name, socket_addr_type* addr)
739 name = reinterpret_cast<T>(addr);
742 template <typename T>
743 inline void init_msghdr_msg_name(T& name, const socket_addr_type* addr)
745 name = reinterpret_cast<T>(const_cast<socket_addr_type*>(addr));
748 signed_size_type recv(socket_type s, buf* bufs, size_t count,
749 int flags, boost::system::error_code& ec)
751 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
752 // Receive some data.
753 DWORD recv_buf_count = static_cast<DWORD>(count);
754 DWORD bytes_transferred = 0;
755 DWORD recv_flags = flags;
756 int result = ::WSARecv(s, bufs, recv_buf_count,
757 &bytes_transferred, &recv_flags, 0, 0);
758 get_last_error(ec, true);
759 if (ec.value() == ERROR_NETNAME_DELETED)
760 ec = boost::asio::error::connection_reset;
761 else if (ec.value() == ERROR_PORT_UNREACHABLE)
762 ec = boost::asio::error::connection_refused;
763 else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
766 return socket_error_retval;
767 ec.assign(0, ec.category());
768 return bytes_transferred;
769 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
770 msghdr msg = msghdr();
772 msg.msg_iovlen = static_cast<int>(count);
773 signed_size_type result = ::recvmsg(s, &msg, flags);
774 get_last_error(ec, result < 0);
776 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
779 signed_size_type recv1(socket_type s, void* data, size_t size,
780 int flags, boost::system::error_code& ec)
782 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
783 // Receive some data.
785 buf.buf = const_cast<char*>(static_cast<const char*>(data));
786 buf.len = static_cast<ULONG>(size);
787 DWORD bytes_transferred = 0;
788 DWORD recv_flags = flags;
789 int result = ::WSARecv(s, &buf, 1,
790 &bytes_transferred, &recv_flags, 0, 0);
791 get_last_error(ec, true);
792 if (ec.value() == ERROR_NETNAME_DELETED)
793 ec = boost::asio::error::connection_reset;
794 else if (ec.value() == ERROR_PORT_UNREACHABLE)
795 ec = boost::asio::error::connection_refused;
796 else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
799 return socket_error_retval;
800 ec.assign(0, ec.category());
801 return bytes_transferred;
802 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
803 signed_size_type result = ::recv(s, static_cast<char*>(data), size, flags);
804 get_last_error(ec, result < 0);
806 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
809 size_t sync_recv(socket_type s, state_type state, buf* bufs,
810 size_t count, int flags, bool all_empty, boost::system::error_code& ec)
812 if (s == invalid_socket)
814 ec = boost::asio::error::bad_descriptor;
818 // A request to read 0 bytes on a stream is a no-op.
819 if (all_empty && (state & stream_oriented))
821 ec.assign(0, ec.category());
828 // Try to complete the operation without blocking.
829 signed_size_type bytes = socket_ops::recv(s, bufs, count, flags, ec);
832 if ((state & stream_oriented) && bytes == 0)
834 ec = boost::asio::error::eof;
838 // Check if operation succeeded.
843 if ((state & user_set_non_blocking)
844 || (ec != boost::asio::error::would_block
845 && ec != boost::asio::error::try_again))
848 // Wait for socket to become ready.
849 if (socket_ops::poll_read(s, 0, -1, ec) < 0)
854 size_t sync_recv1(socket_type s, state_type state, void* data,
855 size_t size, int flags, boost::system::error_code& ec)
857 if (s == invalid_socket)
859 ec = boost::asio::error::bad_descriptor;
863 // A request to read 0 bytes on a stream is a no-op.
864 if (size == 0 && (state & stream_oriented))
866 ec.assign(0, ec.category());
873 // Try to complete the operation without blocking.
874 signed_size_type bytes = socket_ops::recv1(s, data, size, flags, ec);
877 if ((state & stream_oriented) && bytes == 0)
879 ec = boost::asio::error::eof;
883 // Check if operation succeeded.
888 if ((state & user_set_non_blocking)
889 || (ec != boost::asio::error::would_block
890 && ec != boost::asio::error::try_again))
893 // Wait for socket to become ready.
894 if (socket_ops::poll_read(s, 0, -1, ec) < 0)
899 #if defined(BOOST_ASIO_HAS_IOCP)
901 void complete_iocp_recv(state_type state,
902 const weak_cancel_token_type& cancel_token, bool all_empty,
903 boost::system::error_code& ec, size_t bytes_transferred)
905 // Map non-portable errors to their portable counterparts.
906 if (ec.value() == ERROR_NETNAME_DELETED)
908 if (cancel_token.expired())
909 ec = boost::asio::error::operation_aborted;
911 ec = boost::asio::error::connection_reset;
913 else if (ec.value() == ERROR_PORT_UNREACHABLE)
915 ec = boost::asio::error::connection_refused;
917 else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
919 ec.assign(0, ec.category());
922 // Check for connection closed.
923 else if (!ec && bytes_transferred == 0
924 && (state & stream_oriented) != 0
927 ec = boost::asio::error::eof;
931 #else // defined(BOOST_ASIO_HAS_IOCP)
933 bool non_blocking_recv(socket_type s,
934 buf* bufs, size_t count, int flags, bool is_stream,
935 boost::system::error_code& ec, size_t& bytes_transferred)
940 signed_size_type bytes = socket_ops::recv(s, bufs, count, flags, ec);
942 // Check for end of stream.
943 if (is_stream && bytes == 0)
945 ec = boost::asio::error::eof;
949 // Check if operation succeeded.
952 bytes_transferred = bytes;
956 // Retry operation if interrupted by signal.
957 if (ec == boost::asio::error::interrupted)
960 // Check if we need to run the operation again.
961 if (ec == boost::asio::error::would_block
962 || ec == boost::asio::error::try_again)
966 bytes_transferred = 0;
971 bool non_blocking_recv1(socket_type s,
972 void* data, size_t size, int flags, bool is_stream,
973 boost::system::error_code& ec, size_t& bytes_transferred)
978 signed_size_type bytes = socket_ops::recv1(s, data, size, flags, ec);
980 // Check for end of stream.
981 if (is_stream && bytes == 0)
983 ec = boost::asio::error::eof;
987 // Check if operation succeeded.
990 bytes_transferred = bytes;
994 // Retry operation if interrupted by signal.
995 if (ec == boost::asio::error::interrupted)
998 // Check if we need to run the operation again.
999 if (ec == boost::asio::error::would_block
1000 || ec == boost::asio::error::try_again)
1003 // Operation failed.
1004 bytes_transferred = 0;
1009 #endif // defined(BOOST_ASIO_HAS_IOCP)
1011 signed_size_type recvfrom(socket_type s, buf* bufs, size_t count,
1012 int flags, socket_addr_type* addr, std::size_t* addrlen,
1013 boost::system::error_code& ec)
1015 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1016 // Receive some data.
1017 DWORD recv_buf_count = static_cast<DWORD>(count);
1018 DWORD bytes_transferred = 0;
1019 DWORD recv_flags = flags;
1020 int tmp_addrlen = (int)*addrlen;
1021 int result = ::WSARecvFrom(s, bufs, recv_buf_count,
1022 &bytes_transferred, &recv_flags, addr, &tmp_addrlen, 0, 0);
1023 get_last_error(ec, true);
1024 *addrlen = (std::size_t)tmp_addrlen;
1025 if (ec.value() == ERROR_NETNAME_DELETED)
1026 ec = boost::asio::error::connection_reset;
1027 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1028 ec = boost::asio::error::connection_refused;
1029 else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
1032 return socket_error_retval;
1033 ec.assign(0, ec.category());
1034 return bytes_transferred;
1035 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1036 msghdr msg = msghdr();
1037 init_msghdr_msg_name(msg.msg_name, addr);
1038 msg.msg_namelen = static_cast<int>(*addrlen);
1040 msg.msg_iovlen = static_cast<int>(count);
1041 signed_size_type result = ::recvmsg(s, &msg, flags);
1042 get_last_error(ec, result < 0);
1043 *addrlen = msg.msg_namelen;
1045 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1048 template <typename SockLenType>
1049 inline signed_size_type call_recvfrom(SockLenType msghdr::*,
1050 socket_type s, void* data, size_t size, int flags,
1051 socket_addr_type* addr, std::size_t* addrlen)
1053 SockLenType tmp_addrlen = addrlen ? (SockLenType)*addrlen : 0;
1054 signed_size_type result = ::recvfrom(s, static_cast<char*>(data),
1055 size, flags, addr, addrlen ? &tmp_addrlen : 0);
1057 *addrlen = (std::size_t)tmp_addrlen;
1061 signed_size_type recvfrom1(socket_type s, void* data, size_t size,
1062 int flags, socket_addr_type* addr, std::size_t* addrlen,
1063 boost::system::error_code& ec)
1065 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1066 // Receive some data.
1068 buf.buf = static_cast<char*>(data);
1069 buf.len = static_cast<ULONG>(size);
1070 DWORD bytes_transferred = 0;
1071 DWORD recv_flags = flags;
1072 int tmp_addrlen = (int)*addrlen;
1073 int result = ::WSARecvFrom(s, &buf, 1, &bytes_transferred,
1074 &recv_flags, addr, &tmp_addrlen, 0, 0);
1075 get_last_error(ec, true);
1076 *addrlen = (std::size_t)tmp_addrlen;
1077 if (ec.value() == ERROR_NETNAME_DELETED)
1078 ec = boost::asio::error::connection_reset;
1079 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1080 ec = boost::asio::error::connection_refused;
1081 else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
1084 return socket_error_retval;
1085 ec.assign(0, ec.category());
1086 return bytes_transferred;
1087 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1088 signed_size_type result = call_recvfrom(&msghdr::msg_namelen,
1089 s, data, size, flags, addr, addrlen);
1090 get_last_error(ec, result < 0);
1092 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1095 size_t sync_recvfrom(socket_type s, state_type state, buf* bufs,
1096 size_t count, int flags, socket_addr_type* addr,
1097 std::size_t* addrlen, boost::system::error_code& ec)
1099 if (s == invalid_socket)
1101 ec = boost::asio::error::bad_descriptor;
1108 // Try to complete the operation without blocking.
1109 signed_size_type bytes = socket_ops::recvfrom(
1110 s, bufs, count, flags, addr, addrlen, ec);
1112 // Check if operation succeeded.
1116 // Operation failed.
1117 if ((state & user_set_non_blocking)
1118 || (ec != boost::asio::error::would_block
1119 && ec != boost::asio::error::try_again))
1122 // Wait for socket to become ready.
1123 if (socket_ops::poll_read(s, 0, -1, ec) < 0)
1128 size_t sync_recvfrom1(socket_type s, state_type state, void* data,
1129 size_t size, int flags, socket_addr_type* addr,
1130 std::size_t* addrlen, boost::system::error_code& ec)
1132 if (s == invalid_socket)
1134 ec = boost::asio::error::bad_descriptor;
1141 // Try to complete the operation without blocking.
1142 signed_size_type bytes = socket_ops::recvfrom1(
1143 s, data, size, flags, addr, addrlen, ec);
1145 // Check if operation succeeded.
1149 // Operation failed.
1150 if ((state & user_set_non_blocking)
1151 || (ec != boost::asio::error::would_block
1152 && ec != boost::asio::error::try_again))
1155 // Wait for socket to become ready.
1156 if (socket_ops::poll_read(s, 0, -1, ec) < 0)
1161 #if defined(BOOST_ASIO_HAS_IOCP)
1163 void complete_iocp_recvfrom(
1164 const weak_cancel_token_type& cancel_token,
1165 boost::system::error_code& ec)
1167 // Map non-portable errors to their portable counterparts.
1168 if (ec.value() == ERROR_NETNAME_DELETED)
1170 if (cancel_token.expired())
1171 ec = boost::asio::error::operation_aborted;
1173 ec = boost::asio::error::connection_reset;
1175 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1177 ec = boost::asio::error::connection_refused;
1179 else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
1181 ec.assign(0, ec.category());
1185 #else // defined(BOOST_ASIO_HAS_IOCP)
1187 bool non_blocking_recvfrom(socket_type s,
1188 buf* bufs, size_t count, int flags,
1189 socket_addr_type* addr, std::size_t* addrlen,
1190 boost::system::error_code& ec, size_t& bytes_transferred)
1195 signed_size_type bytes = socket_ops::recvfrom(
1196 s, bufs, count, flags, addr, addrlen, ec);
1198 // Check if operation succeeded.
1201 bytes_transferred = bytes;
1205 // Retry operation if interrupted by signal.
1206 if (ec == boost::asio::error::interrupted)
1209 // Check if we need to run the operation again.
1210 if (ec == boost::asio::error::would_block
1211 || ec == boost::asio::error::try_again)
1214 // Operation failed.
1215 bytes_transferred = 0;
1220 bool non_blocking_recvfrom1(socket_type s,
1221 void* data, size_t size, int flags,
1222 socket_addr_type* addr, std::size_t* addrlen,
1223 boost::system::error_code& ec, size_t& bytes_transferred)
1228 signed_size_type bytes = socket_ops::recvfrom1(
1229 s, data, size, flags, addr, addrlen, ec);
1231 // Check if operation succeeded.
1234 bytes_transferred = bytes;
1238 // Retry operation if interrupted by signal.
1239 if (ec == boost::asio::error::interrupted)
1242 // Check if we need to run the operation again.
1243 if (ec == boost::asio::error::would_block
1244 || ec == boost::asio::error::try_again)
1247 // Operation failed.
1248 bytes_transferred = 0;
1253 #endif // defined(BOOST_ASIO_HAS_IOCP)
1255 signed_size_type recvmsg(socket_type s, buf* bufs, size_t count,
1256 int in_flags, int& out_flags, boost::system::error_code& ec)
1258 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1260 return socket_ops::recv(s, bufs, count, in_flags, ec);
1261 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1262 msghdr msg = msghdr();
1264 msg.msg_iovlen = static_cast<int>(count);
1265 signed_size_type result = ::recvmsg(s, &msg, in_flags);
1266 get_last_error(ec, result < 0);
1268 out_flags = msg.msg_flags;
1272 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1275 size_t sync_recvmsg(socket_type s, state_type state,
1276 buf* bufs, size_t count, int in_flags, int& out_flags,
1277 boost::system::error_code& ec)
1279 if (s == invalid_socket)
1281 ec = boost::asio::error::bad_descriptor;
1288 // Try to complete the operation without blocking.
1289 signed_size_type bytes = socket_ops::recvmsg(
1290 s, bufs, count, in_flags, out_flags, ec);
1292 // Check if operation succeeded.
1296 // Operation failed.
1297 if ((state & user_set_non_blocking)
1298 || (ec != boost::asio::error::would_block
1299 && ec != boost::asio::error::try_again))
1302 // Wait for socket to become ready.
1303 if (socket_ops::poll_read(s, 0, -1, ec) < 0)
1308 #if defined(BOOST_ASIO_HAS_IOCP)
1310 void complete_iocp_recvmsg(
1311 const weak_cancel_token_type& cancel_token,
1312 boost::system::error_code& ec)
1314 // Map non-portable errors to their portable counterparts.
1315 if (ec.value() == ERROR_NETNAME_DELETED)
1317 if (cancel_token.expired())
1318 ec = boost::asio::error::operation_aborted;
1320 ec = boost::asio::error::connection_reset;
1322 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1324 ec = boost::asio::error::connection_refused;
1326 else if (ec.value() == WSAEMSGSIZE || ec.value() == ERROR_MORE_DATA)
1328 ec.assign(0, ec.category());
1332 #else // defined(BOOST_ASIO_HAS_IOCP)
1334 bool non_blocking_recvmsg(socket_type s,
1335 buf* bufs, size_t count, int in_flags, int& out_flags,
1336 boost::system::error_code& ec, size_t& bytes_transferred)
1341 signed_size_type bytes = socket_ops::recvmsg(
1342 s, bufs, count, in_flags, out_flags, ec);
1344 // Check if operation succeeded.
1347 bytes_transferred = bytes;
1351 // Retry operation if interrupted by signal.
1352 if (ec == boost::asio::error::interrupted)
1355 // Check if we need to run the operation again.
1356 if (ec == boost::asio::error::would_block
1357 || ec == boost::asio::error::try_again)
1360 // Operation failed.
1361 bytes_transferred = 0;
1366 #endif // defined(BOOST_ASIO_HAS_IOCP)
1368 signed_size_type send(socket_type s, const buf* bufs, size_t count,
1369 int flags, boost::system::error_code& ec)
1371 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1373 DWORD send_buf_count = static_cast<DWORD>(count);
1374 DWORD bytes_transferred = 0;
1375 DWORD send_flags = flags;
1376 int result = ::WSASend(s, const_cast<buf*>(bufs),
1377 send_buf_count, &bytes_transferred, send_flags, 0, 0);
1378 get_last_error(ec, true);
1379 if (ec.value() == ERROR_NETNAME_DELETED)
1380 ec = boost::asio::error::connection_reset;
1381 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1382 ec = boost::asio::error::connection_refused;
1384 return socket_error_retval;
1385 ec.assign(0, ec.category());
1386 return bytes_transferred;
1387 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1388 msghdr msg = msghdr();
1389 msg.msg_iov = const_cast<buf*>(bufs);
1390 msg.msg_iovlen = static_cast<int>(count);
1391 #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1392 flags |= MSG_NOSIGNAL;
1393 #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1394 signed_size_type result = ::sendmsg(s, &msg, flags);
1395 get_last_error(ec, result < 0);
1397 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1400 signed_size_type send1(socket_type s, const void* data, size_t size,
1401 int flags, boost::system::error_code& ec)
1403 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1406 buf.buf = const_cast<char*>(static_cast<const char*>(data));
1407 buf.len = static_cast<ULONG>(size);
1408 DWORD bytes_transferred = 0;
1409 DWORD send_flags = flags;
1410 int result = ::WSASend(s, &buf, 1,
1411 &bytes_transferred, send_flags, 0, 0);
1412 get_last_error(ec, true);
1413 if (ec.value() == ERROR_NETNAME_DELETED)
1414 ec = boost::asio::error::connection_reset;
1415 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1416 ec = boost::asio::error::connection_refused;
1418 return socket_error_retval;
1419 ec.assign(0, ec.category());
1420 return bytes_transferred;
1421 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1422 #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1423 flags |= MSG_NOSIGNAL;
1424 #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1425 signed_size_type result = ::send(s,
1426 static_cast<const char*>(data), size, flags);
1427 get_last_error(ec, result < 0);
1429 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1432 size_t sync_send(socket_type s, state_type state, const buf* bufs,
1433 size_t count, int flags, bool all_empty, boost::system::error_code& ec)
1435 if (s == invalid_socket)
1437 ec = boost::asio::error::bad_descriptor;
1441 // A request to write 0 bytes to a stream is a no-op.
1442 if (all_empty && (state & stream_oriented))
1444 ec.assign(0, ec.category());
1451 // Try to complete the operation without blocking.
1452 signed_size_type bytes = socket_ops::send(s, bufs, count, flags, ec);
1454 // Check if operation succeeded.
1458 // Operation failed.
1459 if ((state & user_set_non_blocking)
1460 || (ec != boost::asio::error::would_block
1461 && ec != boost::asio::error::try_again))
1464 // Wait for socket to become ready.
1465 if (socket_ops::poll_write(s, 0, -1, ec) < 0)
1470 size_t sync_send1(socket_type s, state_type state, const void* data,
1471 size_t size, int flags, boost::system::error_code& ec)
1473 if (s == invalid_socket)
1475 ec = boost::asio::error::bad_descriptor;
1479 // A request to write 0 bytes to a stream is a no-op.
1480 if (size == 0 && (state & stream_oriented))
1482 ec.assign(0, ec.category());
1489 // Try to complete the operation without blocking.
1490 signed_size_type bytes = socket_ops::send1(s, data, size, flags, ec);
1492 // Check if operation succeeded.
1496 // Operation failed.
1497 if ((state & user_set_non_blocking)
1498 || (ec != boost::asio::error::would_block
1499 && ec != boost::asio::error::try_again))
1502 // Wait for socket to become ready.
1503 if (socket_ops::poll_write(s, 0, -1, ec) < 0)
1508 #if defined(BOOST_ASIO_HAS_IOCP)
1510 void complete_iocp_send(
1511 const weak_cancel_token_type& cancel_token,
1512 boost::system::error_code& ec)
1514 // Map non-portable errors to their portable counterparts.
1515 if (ec.value() == ERROR_NETNAME_DELETED)
1517 if (cancel_token.expired())
1518 ec = boost::asio::error::operation_aborted;
1520 ec = boost::asio::error::connection_reset;
1522 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1524 ec = boost::asio::error::connection_refused;
1528 #else // defined(BOOST_ASIO_HAS_IOCP)
1530 bool non_blocking_send(socket_type s,
1531 const buf* bufs, size_t count, int flags,
1532 boost::system::error_code& ec, size_t& bytes_transferred)
1537 signed_size_type bytes = socket_ops::send(s, bufs, count, flags, ec);
1539 // Check if operation succeeded.
1542 bytes_transferred = bytes;
1546 // Retry operation if interrupted by signal.
1547 if (ec == boost::asio::error::interrupted)
1550 // Check if we need to run the operation again.
1551 if (ec == boost::asio::error::would_block
1552 || ec == boost::asio::error::try_again)
1555 // Operation failed.
1556 bytes_transferred = 0;
1561 bool non_blocking_send1(socket_type s,
1562 const void* data, size_t size, int flags,
1563 boost::system::error_code& ec, size_t& bytes_transferred)
1568 signed_size_type bytes = socket_ops::send1(s, data, size, flags, ec);
1570 // Check if operation succeeded.
1573 bytes_transferred = bytes;
1577 // Retry operation if interrupted by signal.
1578 if (ec == boost::asio::error::interrupted)
1581 // Check if we need to run the operation again.
1582 if (ec == boost::asio::error::would_block
1583 || ec == boost::asio::error::try_again)
1586 // Operation failed.
1587 bytes_transferred = 0;
1592 #endif // defined(BOOST_ASIO_HAS_IOCP)
1594 signed_size_type sendto(socket_type s, const buf* bufs, size_t count,
1595 int flags, const socket_addr_type* addr, std::size_t addrlen,
1596 boost::system::error_code& ec)
1598 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1600 DWORD send_buf_count = static_cast<DWORD>(count);
1601 DWORD bytes_transferred = 0;
1602 int result = ::WSASendTo(s, const_cast<buf*>(bufs),
1603 send_buf_count, &bytes_transferred, flags, addr,
1604 static_cast<int>(addrlen), 0, 0);
1605 get_last_error(ec, true);
1606 if (ec.value() == ERROR_NETNAME_DELETED)
1607 ec = boost::asio::error::connection_reset;
1608 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1609 ec = boost::asio::error::connection_refused;
1611 return socket_error_retval;
1612 ec.assign(0, ec.category());
1613 return bytes_transferred;
1614 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1615 msghdr msg = msghdr();
1616 init_msghdr_msg_name(msg.msg_name, addr);
1617 msg.msg_namelen = static_cast<int>(addrlen);
1618 msg.msg_iov = const_cast<buf*>(bufs);
1619 msg.msg_iovlen = static_cast<int>(count);
1620 #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1621 flags |= MSG_NOSIGNAL;
1622 #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1623 signed_size_type result = ::sendmsg(s, &msg, flags);
1624 get_last_error(ec, result < 0);
1626 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1629 template <typename SockLenType>
1630 inline signed_size_type call_sendto(SockLenType msghdr::*,
1631 socket_type s, const void* data, size_t size, int flags,
1632 const socket_addr_type* addr, std::size_t addrlen)
1634 return ::sendto(s, static_cast<char*>(const_cast<void*>(data)),
1635 size, flags, addr, (SockLenType)addrlen);
1638 signed_size_type sendto1(socket_type s, const void* data, size_t size,
1639 int flags, const socket_addr_type* addr, std::size_t addrlen,
1640 boost::system::error_code& ec)
1642 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1645 buf.buf = const_cast<char*>(static_cast<const char*>(data));
1646 buf.len = static_cast<ULONG>(size);
1647 DWORD bytes_transferred = 0;
1648 int result = ::WSASendTo(s, &buf, 1, &bytes_transferred,
1649 flags, addr, static_cast<int>(addrlen), 0, 0);
1650 get_last_error(ec, true);
1651 if (ec.value() == ERROR_NETNAME_DELETED)
1652 ec = boost::asio::error::connection_reset;
1653 else if (ec.value() == ERROR_PORT_UNREACHABLE)
1654 ec = boost::asio::error::connection_refused;
1656 return socket_error_retval;
1657 ec.assign(0, ec.category());
1658 return bytes_transferred;
1659 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1660 #if defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1661 flags |= MSG_NOSIGNAL;
1662 #endif // defined(BOOST_ASIO_HAS_MSG_NOSIGNAL)
1663 signed_size_type result = call_sendto(&msghdr::msg_namelen,
1664 s, data, size, flags, addr, addrlen);
1665 get_last_error(ec, result < 0);
1667 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1670 size_t sync_sendto(socket_type s, state_type state, const buf* bufs,
1671 size_t count, int flags, const socket_addr_type* addr,
1672 std::size_t addrlen, boost::system::error_code& ec)
1674 if (s == invalid_socket)
1676 ec = boost::asio::error::bad_descriptor;
1683 // Try to complete the operation without blocking.
1684 signed_size_type bytes = socket_ops::sendto(
1685 s, bufs, count, flags, addr, addrlen, ec);
1687 // Check if operation succeeded.
1691 // Operation failed.
1692 if ((state & user_set_non_blocking)
1693 || (ec != boost::asio::error::would_block
1694 && ec != boost::asio::error::try_again))
1697 // Wait for socket to become ready.
1698 if (socket_ops::poll_write(s, 0, -1, ec) < 0)
1703 size_t sync_sendto1(socket_type s, state_type state, const void* data,
1704 size_t size, int flags, const socket_addr_type* addr,
1705 std::size_t addrlen, boost::system::error_code& ec)
1707 if (s == invalid_socket)
1709 ec = boost::asio::error::bad_descriptor;
1716 // Try to complete the operation without blocking.
1717 signed_size_type bytes = socket_ops::sendto1(
1718 s, data, size, flags, addr, addrlen, ec);
1720 // Check if operation succeeded.
1724 // Operation failed.
1725 if ((state & user_set_non_blocking)
1726 || (ec != boost::asio::error::would_block
1727 && ec != boost::asio::error::try_again))
1730 // Wait for socket to become ready.
1731 if (socket_ops::poll_write(s, 0, -1, ec) < 0)
1736 #if !defined(BOOST_ASIO_HAS_IOCP)
1738 bool non_blocking_sendto(socket_type s,
1739 const buf* bufs, size_t count, int flags,
1740 const socket_addr_type* addr, std::size_t addrlen,
1741 boost::system::error_code& ec, size_t& bytes_transferred)
1746 signed_size_type bytes = socket_ops::sendto(
1747 s, bufs, count, flags, addr, addrlen, ec);
1749 // Check if operation succeeded.
1752 bytes_transferred = bytes;
1756 // Retry operation if interrupted by signal.
1757 if (ec == boost::asio::error::interrupted)
1760 // Check if we need to run the operation again.
1761 if (ec == boost::asio::error::would_block
1762 || ec == boost::asio::error::try_again)
1765 // Operation failed.
1766 bytes_transferred = 0;
1771 bool non_blocking_sendto1(socket_type s,
1772 const void* data, size_t size, int flags,
1773 const socket_addr_type* addr, std::size_t addrlen,
1774 boost::system::error_code& ec, size_t& bytes_transferred)
1779 signed_size_type bytes = socket_ops::sendto1(
1780 s, data, size, flags, addr, addrlen, ec);
1782 // Check if operation succeeded.
1785 bytes_transferred = bytes;
1789 // Retry operation if interrupted by signal.
1790 if (ec == boost::asio::error::interrupted)
1793 // Check if we need to run the operation again.
1794 if (ec == boost::asio::error::would_block
1795 || ec == boost::asio::error::try_again)
1798 // Operation failed.
1799 bytes_transferred = 0;
1804 #endif // !defined(BOOST_ASIO_HAS_IOCP)
1806 socket_type socket(int af, int type, int protocol,
1807 boost::system::error_code& ec)
1809 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
1810 socket_type s = ::WSASocketW(af, type, protocol, 0, 0, WSA_FLAG_OVERLAPPED);
1811 get_last_error(ec, s == invalid_socket);
1812 if (s == invalid_socket)
1815 if (af == BOOST_ASIO_OS_DEF(AF_INET6))
1817 // Try to enable the POSIX default behaviour of having IPV6_V6ONLY set to
1818 // false. This will only succeed on Windows Vista and later versions of
1819 // Windows, where a dual-stack IPv4/v6 implementation is available.
1821 ::setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
1822 reinterpret_cast<const char*>(&optval), sizeof(optval));
1826 #elif defined(__MACH__) && defined(__APPLE__) || defined(__FreeBSD__)
1827 socket_type s = ::socket(af, type, protocol);
1828 get_last_error(ec, s < 0);
1831 int result = ::setsockopt(s, SOL_SOCKET,
1832 SO_NOSIGPIPE, &optval, sizeof(optval));
1833 get_last_error(ec, result != 0);
1837 return invalid_socket;
1842 int s = ::socket(af, type, protocol);
1843 get_last_error(ec, s < 0);
1848 template <typename SockLenType>
1849 inline int call_setsockopt(SockLenType msghdr::*,
1850 socket_type s, int level, int optname,
1851 const void* optval, std::size_t optlen)
1853 return ::setsockopt(s, level, optname,
1854 (const char*)optval, (SockLenType)optlen);
1857 int setsockopt(socket_type s, state_type& state, int level, int optname,
1858 const void* optval, std::size_t optlen, boost::system::error_code& ec)
1860 if (s == invalid_socket)
1862 ec = boost::asio::error::bad_descriptor;
1863 return socket_error_retval;
1866 if (level == custom_socket_option_level && optname == always_fail_option)
1868 ec = boost::asio::error::invalid_argument;
1869 return socket_error_retval;
1872 if (level == custom_socket_option_level
1873 && optname == enable_connection_aborted_option)
1875 if (optlen != sizeof(int))
1877 ec = boost::asio::error::invalid_argument;
1878 return socket_error_retval;
1881 if (*static_cast<const int*>(optval))
1882 state |= enable_connection_aborted;
1884 state &= ~enable_connection_aborted;
1885 ec.assign(0, ec.category());
1889 if (level == SOL_SOCKET && optname == SO_LINGER)
1890 state |= user_set_linger;
1892 #if defined(__BORLANDC__)
1893 // Mysteriously, using the getsockopt and setsockopt functions directly with
1894 // Borland C++ results in incorrect values being set and read. The bug can be
1895 // worked around by using function addresses resolved with GetProcAddress.
1896 if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
1898 typedef int (WSAAPI *sso_t)(SOCKET, int, int, const char*, int);
1899 if (sso_t sso = (sso_t)::GetProcAddress(winsock_module, "setsockopt"))
1901 int result = sso(s, level, optname,
1902 reinterpret_cast<const char*>(optval),
1903 static_cast<int>(optlen));
1904 get_last_error(ec, result != 0);
1908 ec = boost::asio::error::fault;
1909 return socket_error_retval;
1910 #else // defined(__BORLANDC__)
1911 int result = call_setsockopt(&msghdr::msg_namelen,
1912 s, level, optname, optval, optlen);
1913 get_last_error(ec, result != 0);
1916 #if defined(__MACH__) && defined(__APPLE__) \
1917 || defined(__NetBSD__) || defined(__FreeBSD__) \
1918 || defined(__OpenBSD__) || defined(__QNX__)
1919 // To implement portable behaviour for SO_REUSEADDR with UDP sockets we
1920 // need to also set SO_REUSEPORT on BSD-based platforms.
1921 if ((state & datagram_oriented)
1922 && level == SOL_SOCKET && optname == SO_REUSEADDR)
1924 call_setsockopt(&msghdr::msg_namelen, s,
1925 SOL_SOCKET, SO_REUSEPORT, optval, optlen);
1931 #endif // defined(__BORLANDC__)
1934 template <typename SockLenType>
1935 inline int call_getsockopt(SockLenType msghdr::*,
1936 socket_type s, int level, int optname,
1937 void* optval, std::size_t* optlen)
1939 SockLenType tmp_optlen = (SockLenType)*optlen;
1940 int result = ::getsockopt(s, level, optname, (char*)optval, &tmp_optlen);
1941 *optlen = (std::size_t)tmp_optlen;
1945 int getsockopt(socket_type s, state_type state, int level, int optname,
1946 void* optval, size_t* optlen, boost::system::error_code& ec)
1948 if (s == invalid_socket)
1950 ec = boost::asio::error::bad_descriptor;
1951 return socket_error_retval;
1954 if (level == custom_socket_option_level && optname == always_fail_option)
1956 ec = boost::asio::error::invalid_argument;
1957 return socket_error_retval;
1960 if (level == custom_socket_option_level
1961 && optname == enable_connection_aborted_option)
1963 if (*optlen != sizeof(int))
1965 ec = boost::asio::error::invalid_argument;
1966 return socket_error_retval;
1969 *static_cast<int*>(optval) = (state & enable_connection_aborted) ? 1 : 0;
1970 ec.assign(0, ec.category());
1974 #if defined(__BORLANDC__)
1975 // Mysteriously, using the getsockopt and setsockopt functions directly with
1976 // Borland C++ results in incorrect values being set and read. The bug can be
1977 // worked around by using function addresses resolved with GetProcAddress.
1978 if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
1980 typedef int (WSAAPI *gso_t)(SOCKET, int, int, char*, int*);
1981 if (gso_t gso = (gso_t)::GetProcAddress(winsock_module, "getsockopt"))
1983 int tmp_optlen = static_cast<int>(*optlen);
1984 int result = gso(s, level, optname,
1985 reinterpret_cast<char*>(optval), &tmp_optlen);
1986 get_last_error(ec, result != 0);
1987 *optlen = static_cast<size_t>(tmp_optlen);
1988 if (result != 0 && level == IPPROTO_IPV6 && optname == IPV6_V6ONLY
1989 && ec.value() == WSAENOPROTOOPT && *optlen == sizeof(DWORD))
1991 // Dual-stack IPv4/v6 sockets, and the IPV6_V6ONLY socket option, are
1992 // only supported on Windows Vista and later. To simplify program logic
1993 // we will fake success of getting this option and specify that the
1994 // value is non-zero (i.e. true). This corresponds to the behavior of
1995 // IPv6 sockets on Windows platforms pre-Vista.
1996 *static_cast<DWORD*>(optval) = 1;
1997 ec.assign(0, ec.category());
2002 ec = boost::asio::error::fault;
2003 return socket_error_retval;
2004 #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2005 int result = call_getsockopt(&msghdr::msg_namelen,
2006 s, level, optname, optval, optlen);
2007 get_last_error(ec, result != 0);
2008 if (result != 0 && level == IPPROTO_IPV6 && optname == IPV6_V6ONLY
2009 && ec.value() == WSAENOPROTOOPT && *optlen == sizeof(DWORD))
2011 // Dual-stack IPv4/v6 sockets, and the IPV6_V6ONLY socket option, are only
2012 // supported on Windows Vista and later. To simplify program logic we will
2013 // fake success of getting this option and specify that the value is
2014 // non-zero (i.e. true). This corresponds to the behavior of IPv6 sockets
2015 // on Windows platforms pre-Vista.
2016 *static_cast<DWORD*>(optval) = 1;
2017 ec.assign(0, ec.category());
2020 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2021 int result = call_getsockopt(&msghdr::msg_namelen,
2022 s, level, optname, optval, optlen);
2023 get_last_error(ec, result != 0);
2024 #if defined(__linux__)
2025 if (result == 0 && level == SOL_SOCKET && *optlen == sizeof(int)
2026 && (optname == SO_SNDBUF || optname == SO_RCVBUF))
2028 // On Linux, setting SO_SNDBUF or SO_RCVBUF to N actually causes the kernel
2029 // to set the buffer size to N*2. Linux puts additional stuff into the
2030 // buffers so that only about half is actually available to the application.
2031 // The retrieved value is divided by 2 here to make it appear as though the
2032 // correct value has been set.
2033 *static_cast<int*>(optval) /= 2;
2035 #endif // defined(__linux__)
2037 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2040 template <typename SockLenType>
2041 inline int call_getpeername(SockLenType msghdr::*,
2042 socket_type s, socket_addr_type* addr, std::size_t* addrlen)
2044 SockLenType tmp_addrlen = (SockLenType)*addrlen;
2045 int result = ::getpeername(s, addr, &tmp_addrlen);
2046 *addrlen = (std::size_t)tmp_addrlen;
2050 int getpeername(socket_type s, socket_addr_type* addr,
2051 std::size_t* addrlen, bool cached, boost::system::error_code& ec)
2053 if (s == invalid_socket)
2055 ec = boost::asio::error::bad_descriptor;
2056 return socket_error_retval;
2059 #if defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_WINDOWS_APP) \
2060 || defined(__CYGWIN__)
2063 // Check if socket is still connected.
2064 DWORD connect_time = 0;
2065 size_t connect_time_len = sizeof(connect_time);
2066 if (socket_ops::getsockopt(s, 0, SOL_SOCKET, SO_CONNECT_TIME,
2067 &connect_time, &connect_time_len, ec) == socket_error_retval)
2069 return socket_error_retval;
2071 if (connect_time == 0xFFFFFFFF)
2073 ec = boost::asio::error::not_connected;
2074 return socket_error_retval;
2077 // The cached value is still valid.
2078 ec.assign(0, ec.category());
2081 #else // defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_WINDOWS_APP)
2082 // || defined(__CYGWIN__)
2084 #endif // defined(BOOST_ASIO_WINDOWS) && !defined(BOOST_ASIO_WINDOWS_APP)
2085 // || defined(__CYGWIN__)
2087 int result = call_getpeername(&msghdr::msg_namelen, s, addr, addrlen);
2088 get_last_error(ec, result != 0);
2092 template <typename SockLenType>
2093 inline int call_getsockname(SockLenType msghdr::*,
2094 socket_type s, socket_addr_type* addr, std::size_t* addrlen)
2096 SockLenType tmp_addrlen = (SockLenType)*addrlen;
2097 int result = ::getsockname(s, addr, &tmp_addrlen);
2098 *addrlen = (std::size_t)tmp_addrlen;
2102 int getsockname(socket_type s, socket_addr_type* addr,
2103 std::size_t* addrlen, boost::system::error_code& ec)
2105 if (s == invalid_socket)
2107 ec = boost::asio::error::bad_descriptor;
2108 return socket_error_retval;
2111 int result = call_getsockname(&msghdr::msg_namelen, s, addr, addrlen);
2112 get_last_error(ec, result != 0);
2116 int ioctl(socket_type s, state_type& state, int cmd,
2117 ioctl_arg_type* arg, boost::system::error_code& ec)
2119 if (s == invalid_socket)
2121 ec = boost::asio::error::bad_descriptor;
2122 return socket_error_retval;
2125 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2126 int result = ::ioctlsocket(s, cmd, arg);
2127 #elif defined(__MACH__) && defined(__APPLE__) \
2128 || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
2129 int result = ::ioctl(s, static_cast<unsigned int>(cmd), arg);
2131 int result = ::ioctl(s, cmd, arg);
2133 get_last_error(ec, result < 0);
2136 // When updating the non-blocking mode we always perform the ioctl syscall,
2137 // even if the flags would otherwise indicate that the socket is already in
2138 // the correct state. This ensures that the underlying socket is put into
2139 // the state that has been requested by the user. If the ioctl syscall was
2140 // successful then we need to update the flags to match.
2141 if (cmd == static_cast<int>(FIONBIO))
2145 state |= user_set_non_blocking;
2149 // Clearing the non-blocking mode always overrides any internally-set
2150 // non-blocking flag. Any subsequent asynchronous operations will need
2151 // to re-enable non-blocking I/O.
2152 state &= ~(user_set_non_blocking | internal_non_blocking);
2160 int select(int nfds, fd_set* readfds, fd_set* writefds,
2161 fd_set* exceptfds, timeval* timeout, boost::system::error_code& ec)
2163 #if defined(__EMSCRIPTEN__)
2165 #endif // defined(__EMSCRIPTEN__)
2166 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2167 if (!readfds && !writefds && !exceptfds && timeout)
2169 DWORD milliseconds = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
2170 if (milliseconds == 0)
2171 milliseconds = 1; // Force context switch.
2172 ::Sleep(milliseconds);
2173 ec.assign(0, ec.category());
2177 // The select() call allows timeout values measured in microseconds, but the
2178 // system clock (as wrapped by boost::posix_time::microsec_clock) typically
2179 // has a resolution of 10 milliseconds. This can lead to a spinning select
2180 // reactor, meaning increased CPU usage, when waiting for the earliest
2181 // scheduled timeout if it's less than 10 milliseconds away. To avoid a tight
2182 // spin we'll use a minimum timeout of 1 millisecond.
2183 if (timeout && timeout->tv_sec == 0
2184 && timeout->tv_usec > 0 && timeout->tv_usec < 1000)
2185 timeout->tv_usec = 1000;
2186 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2188 #if defined(__hpux) && defined(__SELECT)
2190 ts.tv_sec = timeout ? timeout->tv_sec : 0;
2191 ts.tv_nsec = timeout ? timeout->tv_usec * 1000 : 0;
2192 int result = ::pselect(nfds, readfds,
2193 writefds, exceptfds, timeout ? &ts : 0, 0);
2195 int result = ::select(nfds, readfds, writefds, exceptfds, timeout);
2197 get_last_error(ec, result < 0);
2201 int poll_read(socket_type s, state_type state,
2202 int msec, boost::system::error_code& ec)
2204 if (s == invalid_socket)
2206 ec = boost::asio::error::bad_descriptor;
2207 return socket_error_retval;
2210 #if defined(BOOST_ASIO_WINDOWS) \
2211 || defined(__CYGWIN__) \
2212 || defined(__SYMBIAN32__)
2216 timeval timeout_obj;
2218 if (state & user_set_non_blocking)
2220 timeout_obj.tv_sec = 0;
2221 timeout_obj.tv_usec = 0;
2222 timeout = &timeout_obj;
2226 timeout_obj.tv_sec = msec / 1000;
2227 timeout_obj.tv_usec = (msec % 1000) * 1000;
2228 timeout = &timeout_obj;
2232 int result = ::select(s + 1, &fds, 0, 0, timeout);
2233 get_last_error(ec, result < 0);
2234 #else // defined(BOOST_ASIO_WINDOWS)
2235 // || defined(__CYGWIN__)
2236 // || defined(__SYMBIAN32__)
2239 fds.events = POLLIN;
2241 int timeout = (state & user_set_non_blocking) ? 0 : msec;
2242 int result = ::poll(&fds, 1, timeout);
2243 get_last_error(ec, result < 0);
2244 #endif // defined(BOOST_ASIO_WINDOWS)
2245 // || defined(__CYGWIN__)
2246 // || defined(__SYMBIAN32__)
2248 if (state & user_set_non_blocking)
2249 ec = boost::asio::error::would_block;
2253 int poll_write(socket_type s, state_type state,
2254 int msec, boost::system::error_code& ec)
2256 if (s == invalid_socket)
2258 ec = boost::asio::error::bad_descriptor;
2259 return socket_error_retval;
2262 #if defined(BOOST_ASIO_WINDOWS) \
2263 || defined(__CYGWIN__) \
2264 || defined(__SYMBIAN32__)
2268 timeval timeout_obj;
2270 if (state & user_set_non_blocking)
2272 timeout_obj.tv_sec = 0;
2273 timeout_obj.tv_usec = 0;
2274 timeout = &timeout_obj;
2278 timeout_obj.tv_sec = msec / 1000;
2279 timeout_obj.tv_usec = (msec % 1000) * 1000;
2280 timeout = &timeout_obj;
2284 int result = ::select(s + 1, 0, &fds, 0, timeout);
2285 get_last_error(ec, result < 0);
2286 #else // defined(BOOST_ASIO_WINDOWS)
2287 // || defined(__CYGWIN__)
2288 // || defined(__SYMBIAN32__)
2291 fds.events = POLLOUT;
2293 int timeout = (state & user_set_non_blocking) ? 0 : msec;
2294 int result = ::poll(&fds, 1, timeout);
2295 get_last_error(ec, result < 0);
2296 #endif // defined(BOOST_ASIO_WINDOWS)
2297 // || defined(__CYGWIN__)
2298 // || defined(__SYMBIAN32__)
2300 if (state & user_set_non_blocking)
2301 ec = boost::asio::error::would_block;
2305 int poll_error(socket_type s, state_type state,
2306 int msec, boost::system::error_code& ec)
2308 if (s == invalid_socket)
2310 ec = boost::asio::error::bad_descriptor;
2311 return socket_error_retval;
2314 #if defined(BOOST_ASIO_WINDOWS) \
2315 || defined(__CYGWIN__) \
2316 || defined(__SYMBIAN32__)
2320 timeval timeout_obj;
2322 if (state & user_set_non_blocking)
2324 timeout_obj.tv_sec = 0;
2325 timeout_obj.tv_usec = 0;
2326 timeout = &timeout_obj;
2330 timeout_obj.tv_sec = msec / 1000;
2331 timeout_obj.tv_usec = (msec % 1000) * 1000;
2332 timeout = &timeout_obj;
2336 int result = ::select(s + 1, 0, 0, &fds, timeout);
2337 get_last_error(ec, result < 0);
2338 #else // defined(BOOST_ASIO_WINDOWS)
2339 // || defined(__CYGWIN__)
2340 // || defined(__SYMBIAN32__)
2343 fds.events = POLLPRI | POLLERR | POLLHUP;
2345 int timeout = (state & user_set_non_blocking) ? 0 : msec;
2346 int result = ::poll(&fds, 1, timeout);
2347 get_last_error(ec, result < 0);
2348 #endif // defined(BOOST_ASIO_WINDOWS)
2349 // || defined(__CYGWIN__)
2350 // || defined(__SYMBIAN32__)
2352 if (state & user_set_non_blocking)
2353 ec = boost::asio::error::would_block;
2357 int poll_connect(socket_type s, int msec, boost::system::error_code& ec)
2359 if (s == invalid_socket)
2361 ec = boost::asio::error::bad_descriptor;
2362 return socket_error_retval;
2365 #if defined(BOOST_ASIO_WINDOWS) \
2366 || defined(__CYGWIN__) \
2367 || defined(__SYMBIAN32__)
2369 FD_ZERO(&write_fds);
2370 FD_SET(s, &write_fds);
2372 FD_ZERO(&except_fds);
2373 FD_SET(s, &except_fds);
2374 timeval timeout_obj;
2378 timeout_obj.tv_sec = msec / 1000;
2379 timeout_obj.tv_usec = (msec % 1000) * 1000;
2380 timeout = &timeout_obj;
2384 int result = ::select(s + 1, 0, &write_fds, &except_fds, timeout);
2385 get_last_error(ec, result < 0);
2387 #else // defined(BOOST_ASIO_WINDOWS)
2388 // || defined(__CYGWIN__)
2389 // || defined(__SYMBIAN32__)
2392 fds.events = POLLOUT;
2394 int result = ::poll(&fds, 1, msec);
2395 get_last_error(ec, result < 0);
2397 #endif // defined(BOOST_ASIO_WINDOWS)
2398 // || defined(__CYGWIN__)
2399 // || defined(__SYMBIAN32__)
2402 #endif // !defined(BOOST_ASIO_WINDOWS_RUNTIME)
2404 const char* inet_ntop(int af, const void* src, char* dest, size_t length,
2405 unsigned long scope_id, boost::system::error_code& ec)
2408 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
2409 using namespace std; // For sprintf.
2410 const unsigned char* bytes = static_cast<const unsigned char*>(src);
2411 if (af == BOOST_ASIO_OS_DEF(AF_INET))
2413 sprintf_s(dest, length, "%u.%u.%u.%u",
2414 bytes[0], bytes[1], bytes[2], bytes[3]);
2417 else if (af == BOOST_ASIO_OS_DEF(AF_INET6))
2419 size_t n = 0, b = 0, z = 0;
2420 while (n < length && b < 16)
2422 if (bytes[b] == 0 && bytes[b + 1] == 0 && z == 0)
2424 do b += 2; while (b < 16 && bytes[b] == 0 && bytes[b + 1] == 0);
2425 n += sprintf_s(dest + n, length - n, ":%s", b < 16 ? "" : ":"), ++z;
2429 n += sprintf_s(dest + n, length - n, "%s%x", b ? ":" : "",
2430 (static_cast<u_long_type>(bytes[b]) << 8) | bytes[b + 1]);
2435 n += sprintf_s(dest + n, length - n, "%%%lu", scope_id);
2440 ec = boost::asio::error::address_family_not_supported;
2443 #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2444 using namespace std; // For memcpy.
2446 if (af != BOOST_ASIO_OS_DEF(AF_INET) && af != BOOST_ASIO_OS_DEF(AF_INET6))
2448 ec = boost::asio::error::address_family_not_supported;
2454 socket_addr_type base;
2455 sockaddr_storage_type storage;
2456 sockaddr_in4_type v4;
2457 sockaddr_in6_type v6;
2459 DWORD address_length;
2460 if (af == BOOST_ASIO_OS_DEF(AF_INET))
2462 address_length = sizeof(sockaddr_in4_type);
2463 address.v4.sin_family = BOOST_ASIO_OS_DEF(AF_INET);
2464 address.v4.sin_port = 0;
2465 memcpy(&address.v4.sin_addr, src, sizeof(in4_addr_type));
2469 address_length = sizeof(sockaddr_in6_type);
2470 address.v6.sin6_family = BOOST_ASIO_OS_DEF(AF_INET6);
2471 address.v6.sin6_port = 0;
2472 address.v6.sin6_flowinfo = 0;
2473 address.v6.sin6_scope_id = scope_id;
2474 memcpy(&address.v6.sin6_addr, src, sizeof(in6_addr_type));
2477 DWORD string_length = static_cast<DWORD>(length);
2478 #if defined(BOOST_NO_ANSI_APIS) || (defined(_MSC_VER) && (_MSC_VER >= 1800))
2479 LPWSTR string_buffer = (LPWSTR)_alloca(length * sizeof(WCHAR));
2480 int result = ::WSAAddressToStringW(&address.base,
2481 address_length, 0, string_buffer, &string_length);
2482 get_last_error(ec, true);
2483 ::WideCharToMultiByte(CP_ACP, 0, string_buffer, -1,
2484 dest, static_cast<int>(length), 0, 0);
2486 int result = ::WSAAddressToStringA(&address.base,
2487 address_length, 0, dest, &string_length);
2488 get_last_error(ec, true);
2491 // Windows may set error code on success.
2492 if (result != socket_error_retval)
2493 ec.assign(0, ec.category());
2495 // Windows may not set an error code on failure.
2496 else if (result == socket_error_retval && !ec)
2497 ec = boost::asio::error::invalid_argument;
2499 return result == socket_error_retval ? 0 : dest;
2500 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2501 const char* result = ::inet_ntop(af, src, dest, static_cast<int>(length));
2502 get_last_error(ec, true);
2503 if (result == 0 && !ec)
2504 ec = boost::asio::error::invalid_argument;
2505 if (result != 0 && af == BOOST_ASIO_OS_DEF(AF_INET6) && scope_id != 0)
2507 using namespace std; // For strcat and sprintf.
2508 char if_name[(IF_NAMESIZE > 21 ? IF_NAMESIZE : 21) + 1] = "%";
2509 const in6_addr_type* ipv6_address = static_cast<const in6_addr_type*>(src);
2510 bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
2511 && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
2512 bool is_multicast_link_local = ((ipv6_address->s6_addr[0] == 0xff)
2513 && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02));
2514 if ((!is_link_local && !is_multicast_link_local)
2515 || if_indextoname(static_cast<unsigned>(scope_id), if_name + 1) == 0)
2516 sprintf(if_name + 1, "%lu", scope_id);
2517 strcat(dest, if_name);
2520 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2523 int inet_pton(int af, const char* src, void* dest,
2524 unsigned long* scope_id, boost::system::error_code& ec)
2527 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
2528 using namespace std; // For sscanf.
2529 unsigned char* bytes = static_cast<unsigned char*>(dest);
2530 if (af == BOOST_ASIO_OS_DEF(AF_INET))
2532 unsigned int b0, b1, b2, b3;
2533 if (sscanf_s(src, "%u.%u.%u.%u", &b0, &b1, &b2, &b3) != 4)
2535 ec = boost::asio::error::invalid_argument;
2538 if (b0 > 255 || b1 > 255 || b2 > 255 || b3 > 255)
2540 ec = boost::asio::error::invalid_argument;
2543 bytes[0] = static_cast<unsigned char>(b0);
2544 bytes[1] = static_cast<unsigned char>(b1);
2545 bytes[2] = static_cast<unsigned char>(b2);
2546 bytes[3] = static_cast<unsigned char>(b3);
2547 ec.assign(0, ec.category());
2550 else if (af == BOOST_ASIO_OS_DEF(AF_INET6))
2552 unsigned char* bytes = static_cast<unsigned char*>(dest);
2553 std::memset(bytes, 0, 16);
2554 unsigned char back_bytes[16] = { 0 };
2555 int num_front_bytes = 0, num_back_bytes = 0;
2556 const char* p = src;
2558 enum { fword, fcolon, bword, scope, done } state = fword;
2559 unsigned long current_word = 0;
2560 while (state != done)
2562 if (current_word > 0xFFFF)
2564 ec = boost::asio::error::invalid_argument;
2571 if (*p >= '0' && *p <= '9')
2572 current_word = current_word * 16 + *p++ - '0';
2573 else if (*p >= 'a' && *p <= 'f')
2574 current_word = current_word * 16 + *p++ - 'a' + 10;
2575 else if (*p >= 'A' && *p <= 'F')
2576 current_word = current_word * 16 + *p++ - 'A' + 10;
2579 if (num_front_bytes == 16)
2581 ec = boost::asio::error::invalid_argument;
2585 bytes[num_front_bytes++] = (current_word >> 8) & 0xFF;
2586 bytes[num_front_bytes++] = current_word & 0xFF;
2590 state = fcolon, ++p;
2597 ec = boost::asio::error::invalid_argument;
2611 if (*p >= '0' && *p <= '9')
2612 current_word = current_word * 16 + *p++ - '0';
2613 else if (*p >= 'a' && *p <= 'f')
2614 current_word = current_word * 16 + *p++ - 'a' + 10;
2615 else if (*p >= 'A' && *p <= 'F')
2616 current_word = current_word * 16 + *p++ - 'A' + 10;
2619 if (num_front_bytes + num_back_bytes == 16)
2621 ec = boost::asio::error::invalid_argument;
2625 back_bytes[num_back_bytes++] = (current_word >> 8) & 0xFF;
2626 back_bytes[num_back_bytes++] = current_word & 0xFF;
2637 ec = boost::asio::error::invalid_argument;
2644 if (*p >= '0' && *p <= '9')
2645 current_word = current_word * 10 + *p++ - '0';
2647 *scope_id = current_word, state = done;
2650 ec = boost::asio::error::invalid_argument;
2660 for (int i = 0; i < num_back_bytes; ++i)
2661 bytes[16 - num_back_bytes + i] = back_bytes[i];
2663 ec.assign(0, ec.category());
2668 ec = boost::asio::error::address_family_not_supported;
2671 #elif defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2672 using namespace std; // For memcpy and strcmp.
2674 if (af != BOOST_ASIO_OS_DEF(AF_INET) && af != BOOST_ASIO_OS_DEF(AF_INET6))
2676 ec = boost::asio::error::address_family_not_supported;
2682 socket_addr_type base;
2683 sockaddr_storage_type storage;
2684 sockaddr_in4_type v4;
2685 sockaddr_in6_type v6;
2687 int address_length = sizeof(sockaddr_storage_type);
2688 #if defined(BOOST_NO_ANSI_APIS) || (defined(_MSC_VER) && (_MSC_VER >= 1800))
2689 int num_wide_chars = static_cast<int>(strlen(src)) + 1;
2690 LPWSTR wide_buffer = (LPWSTR)_alloca(num_wide_chars * sizeof(WCHAR));
2691 ::MultiByteToWideChar(CP_ACP, 0, src, -1, wide_buffer, num_wide_chars);
2692 int result = ::WSAStringToAddressW(wide_buffer,
2693 af, 0, &address.base, &address_length);
2694 get_last_error(ec, true);
2696 int result = ::WSAStringToAddressA(const_cast<char*>(src),
2697 af, 0, &address.base, &address_length);
2698 get_last_error(ec, true);
2701 if (af == BOOST_ASIO_OS_DEF(AF_INET))
2703 if (result != socket_error_retval)
2705 memcpy(dest, &address.v4.sin_addr, sizeof(in4_addr_type));
2706 ec.assign(0, ec.category());
2708 else if (strcmp(src, "255.255.255.255") == 0)
2710 static_cast<in4_addr_type*>(dest)->s_addr = INADDR_NONE;
2711 ec.assign(0, ec.category());
2716 if (result != socket_error_retval)
2718 memcpy(dest, &address.v6.sin6_addr, sizeof(in6_addr_type));
2720 *scope_id = address.v6.sin6_scope_id;
2721 ec.assign(0, ec.category());
2725 // Windows may not set an error code on failure.
2726 if (result == socket_error_retval && !ec)
2727 ec = boost::asio::error::invalid_argument;
2729 if (result != socket_error_retval)
2730 ec.assign(0, ec.category());
2732 return result == socket_error_retval ? -1 : 1;
2733 #else // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2734 using namespace std; // For strchr, memcpy and atoi.
2736 // On some platforms, inet_pton fails if an address string contains a scope
2737 // id. Detect and remove the scope id before passing the string to inet_pton.
2738 const bool is_v6 = (af == BOOST_ASIO_OS_DEF(AF_INET6));
2739 const char* if_name = is_v6 ? strchr(src, '%') : 0;
2740 char src_buf[max_addr_v6_str_len + 1];
2741 const char* src_ptr = src;
2744 if (if_name - src > max_addr_v6_str_len)
2746 ec = boost::asio::error::invalid_argument;
2749 memcpy(src_buf, src, if_name - src);
2750 src_buf[if_name - src] = 0;
2754 int result = ::inet_pton(af, src_ptr, dest);
2755 get_last_error(ec, true);
2756 if (result <= 0 && !ec)
2757 ec = boost::asio::error::invalid_argument;
2758 if (result > 0 && is_v6 && scope_id)
2760 using namespace std; // For strchr and atoi.
2764 in6_addr_type* ipv6_address = static_cast<in6_addr_type*>(dest);
2765 bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe)
2766 && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80));
2767 bool is_multicast_link_local = ((ipv6_address->s6_addr[0] == 0xff)
2768 && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02));
2769 if (is_link_local || is_multicast_link_local)
2770 *scope_id = if_nametoindex(if_name + 1);
2772 *scope_id = atoi(if_name + 1);
2776 #endif // defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2779 int gethostname(char* name, int namelen, boost::system::error_code& ec)
2781 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
2784 using namespace Windows::Foundation::Collections;
2785 using namespace Windows::Networking;
2786 using namespace Windows::Networking::Connectivity;
2787 IVectorView<HostName^>^ hostnames = NetworkInformation::GetHostNames();
2788 for (unsigned i = 0; i < hostnames->Size; ++i)
2790 HostName^ hostname = hostnames->GetAt(i);
2791 if (hostname->Type == HostNameType::DomainName)
2793 std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
2794 std::string raw_name = converter.to_bytes(hostname->RawName->Data());
2795 if (namelen > 0 && raw_name.size() < static_cast<std::size_t>(namelen))
2797 strcpy_s(name, namelen, raw_name.c_str());
2804 catch (Platform::Exception^ e)
2806 ec = boost::system::error_code(e->HResult,
2807 boost::system::system_category());
2810 #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
2811 int result = ::gethostname(name, namelen);
2812 get_last_error(ec, result != 0);
2814 #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
2817 #if !defined(BOOST_ASIO_WINDOWS_RUNTIME)
2819 #if !defined(BOOST_ASIO_HAS_GETADDRINFO)
2821 // The following functions are only needed for emulation of getaddrinfo and
2824 inline boost::system::error_code translate_netdb_error(int error)
2829 return boost::system::error_code();
2830 case HOST_NOT_FOUND:
2831 return boost::asio::error::host_not_found;
2833 return boost::asio::error::host_not_found_try_again;
2835 return boost::asio::error::no_recovery;
2837 return boost::asio::error::no_data;
2839 BOOST_ASIO_ASSERT(false);
2840 return boost::asio::error::invalid_argument;
2844 inline hostent* gethostbyaddr(const char* addr, int length, int af,
2845 hostent* result, char* buffer, int buflength, boost::system::error_code& ec)
2847 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2850 hostent* retval = ::gethostbyaddr(addr, length, af);
2851 get_last_error(ec, !retval);
2856 #elif defined(__sun) || defined(__QNX__)
2858 hostent* retval = ::gethostbyaddr_r(addr, length,
2859 af, result, buffer, buflength, &error);
2860 get_last_error(ec, !retval);
2862 ec = translate_netdb_error(error);
2864 #elif defined(__MACH__) && defined(__APPLE__)
2868 hostent* retval = ::getipnodebyaddr(addr, length, af, &error);
2869 get_last_error(ec, !retval);
2871 ec = translate_netdb_error(error);
2877 hostent* retval = 0;
2880 ::gethostbyaddr_r(addr, length, af, result,
2881 buffer, buflength, &retval, &error);
2882 get_last_error(ec, true);
2884 ec = translate_netdb_error(error);
2889 inline hostent* gethostbyname(const char* name, int af, struct hostent* result,
2890 char* buffer, int buflength, int ai_flags, boost::system::error_code& ec)
2892 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
2896 if (af != BOOST_ASIO_OS_DEF(AF_INET))
2898 ec = boost::asio::error::address_family_not_supported;
2901 hostent* retval = ::gethostbyname(name);
2902 get_last_error(ec, !retval);
2907 #elif defined(__sun) || defined(__QNX__)
2909 if (af != BOOST_ASIO_OS_DEF(AF_INET))
2911 ec = boost::asio::error::address_family_not_supported;
2915 hostent* retval = ::gethostbyname_r(name, result, buffer, buflength, &error);
2916 get_last_error(ec, !retval);
2918 ec = translate_netdb_error(error);
2920 #elif defined(__MACH__) && defined(__APPLE__)
2924 hostent* retval = ::getipnodebyname(name, af, ai_flags, &error);
2925 get_last_error(ec, !retval);
2927 ec = translate_netdb_error(error);
2934 if (af != BOOST_ASIO_OS_DEF(AF_INET))
2936 ec = boost::asio::error::address_family_not_supported;
2939 hostent* retval = 0;
2942 ::gethostbyname_r(name, result, buffer, buflength, &retval, &error);
2943 get_last_error(ec, true);
2945 ec = translate_netdb_error(error);
2950 inline void freehostent(hostent* h)
2952 #if defined(__MACH__) && defined(__APPLE__)
2960 // Emulation of getaddrinfo based on implementation in:
2961 // Stevens, W. R., UNIX Network Programming Vol. 1, 2nd Ed., Prentice-Hall 1998.
2969 inline int gai_nsearch(const char* host,
2970 const addrinfo_type* hints, gai_search (&search)[2])
2972 int search_count = 0;
2973 if (host == 0 || host[0] == '\0')
2975 if (hints->ai_flags & AI_PASSIVE)
2977 // No host and AI_PASSIVE implies wildcard bind.
2978 switch (hints->ai_family)
2980 case BOOST_ASIO_OS_DEF(AF_INET):
2981 search[search_count].host = "0.0.0.0";
2982 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
2985 case BOOST_ASIO_OS_DEF(AF_INET6):
2986 search[search_count].host = "0::0";
2987 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
2990 case BOOST_ASIO_OS_DEF(AF_UNSPEC):
2991 search[search_count].host = "0::0";
2992 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
2994 search[search_count].host = "0.0.0.0";
2995 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
3004 // No host and not AI_PASSIVE means connect to local host.
3005 switch (hints->ai_family)
3007 case BOOST_ASIO_OS_DEF(AF_INET):
3008 search[search_count].host = "localhost";
3009 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
3012 case BOOST_ASIO_OS_DEF(AF_INET6):
3013 search[search_count].host = "localhost";
3014 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
3017 case BOOST_ASIO_OS_DEF(AF_UNSPEC):
3018 search[search_count].host = "localhost";
3019 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
3021 search[search_count].host = "localhost";
3022 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
3032 // Host is specified.
3033 switch (hints->ai_family)
3035 case BOOST_ASIO_OS_DEF(AF_INET):
3036 search[search_count].host = host;
3037 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
3040 case BOOST_ASIO_OS_DEF(AF_INET6):
3041 search[search_count].host = host;
3042 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
3045 case BOOST_ASIO_OS_DEF(AF_UNSPEC):
3046 search[search_count].host = host;
3047 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET6);
3049 search[search_count].host = host;
3050 search[search_count].family = BOOST_ASIO_OS_DEF(AF_INET);
3057 return search_count;
3060 template <typename T>
3061 inline T* gai_alloc(std::size_t size = sizeof(T))
3063 using namespace std;
3064 T* p = static_cast<T*>(::operator new(size, std::nothrow));
3070 inline void gai_free(void* p)
3072 ::operator delete(p);
3075 inline void gai_strcpy(char* target, const char* source, std::size_t max_size)
3077 using namespace std;
3078 #if defined(BOOST_ASIO_HAS_SECURE_RTL)
3079 strcpy_s(target, max_size, source);
3080 #else // defined(BOOST_ASIO_HAS_SECURE_RTL)
3083 strncat(target, source, max_size - 1);
3084 #endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
3087 enum { gai_clone_flag = 1 << 30 };
3089 inline int gai_aistruct(addrinfo_type*** next, const addrinfo_type* hints,
3090 const void* addr, int family)
3092 using namespace std;
3094 addrinfo_type* ai = gai_alloc<addrinfo_type>();
3100 *next = &ai->ai_next;
3102 ai->ai_canonname = 0;
3103 ai->ai_socktype = hints->ai_socktype;
3104 if (ai->ai_socktype == 0)
3105 ai->ai_flags |= gai_clone_flag;
3106 ai->ai_protocol = hints->ai_protocol;
3107 ai->ai_family = family;
3109 switch (ai->ai_family)
3111 case BOOST_ASIO_OS_DEF(AF_INET):
3113 sockaddr_in4_type* sinptr = gai_alloc<sockaddr_in4_type>();
3116 sinptr->sin_family = BOOST_ASIO_OS_DEF(AF_INET);
3117 memcpy(&sinptr->sin_addr, addr, sizeof(in4_addr_type));
3118 ai->ai_addr = reinterpret_cast<sockaddr*>(sinptr);
3119 ai->ai_addrlen = sizeof(sockaddr_in4_type);
3122 case BOOST_ASIO_OS_DEF(AF_INET6):
3124 sockaddr_in6_type* sin6ptr = gai_alloc<sockaddr_in6_type>();
3127 sin6ptr->sin6_family = BOOST_ASIO_OS_DEF(AF_INET6);
3128 memcpy(&sin6ptr->sin6_addr, addr, sizeof(in6_addr_type));
3129 ai->ai_addr = reinterpret_cast<sockaddr*>(sin6ptr);
3130 ai->ai_addrlen = sizeof(sockaddr_in6_type);
3140 inline addrinfo_type* gai_clone(addrinfo_type* ai)
3142 using namespace std;
3144 addrinfo_type* new_ai = gai_alloc<addrinfo_type>();
3148 new_ai->ai_next = ai->ai_next;
3149 ai->ai_next = new_ai;
3151 new_ai->ai_flags = 0;
3152 new_ai->ai_family = ai->ai_family;
3153 new_ai->ai_socktype = ai->ai_socktype;
3154 new_ai->ai_protocol = ai->ai_protocol;
3155 new_ai->ai_canonname = 0;
3156 new_ai->ai_addrlen = ai->ai_addrlen;
3157 new_ai->ai_addr = gai_alloc<sockaddr>(ai->ai_addrlen);
3158 memcpy(new_ai->ai_addr, ai->ai_addr, ai->ai_addrlen);
3163 inline int gai_port(addrinfo_type* aihead, int port, int socktype)
3167 for (addrinfo_type* ai = aihead; ai; ai = ai->ai_next)
3169 if (ai->ai_flags & gai_clone_flag)
3171 if (ai->ai_socktype != 0)
3176 // ai now points to newly cloned entry.
3179 else if (ai->ai_socktype != socktype)
3181 // Ignore if mismatch on socket type.
3185 ai->ai_socktype = socktype;
3187 switch (ai->ai_family)
3189 case BOOST_ASIO_OS_DEF(AF_INET):
3191 sockaddr_in4_type* sinptr =
3192 reinterpret_cast<sockaddr_in4_type*>(ai->ai_addr);
3193 sinptr->sin_port = port;
3197 case BOOST_ASIO_OS_DEF(AF_INET6):
3199 sockaddr_in6_type* sin6ptr =
3200 reinterpret_cast<sockaddr_in6_type*>(ai->ai_addr);
3201 sin6ptr->sin6_port = port;
3213 inline int gai_serv(addrinfo_type* aihead,
3214 const addrinfo_type* hints, const char* serv)
3216 using namespace std;
3221 #if defined(AI_NUMERICSERV)
3222 (hints->ai_flags & AI_NUMERICSERV) ||
3224 isdigit(static_cast<unsigned char>(serv[0])))
3226 int port = htons(atoi(serv));
3227 if (hints->ai_socktype)
3229 // Caller specifies socket type.
3230 int rc = gai_port(aihead, port, hints->ai_socktype);
3237 // Caller does not specify socket type.
3238 int rc = gai_port(aihead, port, SOCK_STREAM);
3242 rc = gai_port(aihead, port, SOCK_DGRAM);
3250 // Try service name with TCP first, then UDP.
3251 if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_STREAM)
3253 servent* sptr = getservbyname(serv, "tcp");
3256 int rc = gai_port(aihead, sptr->s_port, SOCK_STREAM);
3262 if (hints->ai_socktype == 0 || hints->ai_socktype == SOCK_DGRAM)
3264 servent* sptr = getservbyname(serv, "udp");
3267 int rc = gai_port(aihead, sptr->s_port, SOCK_DGRAM);
3277 if (hints->ai_socktype == 0)
3279 // All calls to getservbyname() failed.
3284 // Service not supported for socket type.
3292 inline int gai_echeck(const char* host, const char* service,
3293 int flags, int family, int socktype, int protocol)
3298 // Host or service must be specified.
3299 if (host == 0 || host[0] == '\0')
3300 if (service == 0 || service[0] == '\0')
3303 // Check combination of family and socket type.
3306 case BOOST_ASIO_OS_DEF(AF_UNSPEC):
3308 case BOOST_ASIO_OS_DEF(AF_INET):
3309 case BOOST_ASIO_OS_DEF(AF_INET6):
3310 if (service != 0 && service[0] != '\0')
3311 if (socktype != 0 && socktype != SOCK_STREAM && socktype != SOCK_DGRAM)
3312 return EAI_SOCKTYPE;
3321 inline void freeaddrinfo_emulation(addrinfo_type* aihead)
3323 addrinfo_type* ai = aihead;
3326 gai_free(ai->ai_addr);
3327 gai_free(ai->ai_canonname);
3328 addrinfo_type* ainext = ai->ai_next;
3334 inline int getaddrinfo_emulation(const char* host, const char* service,
3335 const addrinfo_type* hintsp, addrinfo_type** result)
3337 // Set up linked list of addrinfo structures.
3338 addrinfo_type* aihead = 0;
3339 addrinfo_type** ainext = &aihead;
3342 // Supply default hints if not specified by caller.
3343 addrinfo_type hints = addrinfo_type();
3344 hints.ai_family = BOOST_ASIO_OS_DEF(AF_UNSPEC);
3348 // If the resolution is not specifically for AF_INET6, remove the AI_V4MAPPED
3349 // and AI_ALL flags.
3350 #if defined(AI_V4MAPPED)
3351 if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET6))
3352 hints.ai_flags &= ~AI_V4MAPPED;
3355 if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET6))
3356 hints.ai_flags &= ~AI_ALL;
3359 // Basic error checking.
3360 int rc = gai_echeck(host, service, hints.ai_flags, hints.ai_family,
3361 hints.ai_socktype, hints.ai_protocol);
3364 freeaddrinfo_emulation(aihead);
3368 gai_search search[2];
3369 int search_count = gai_nsearch(host, &hints, search);
3370 for (gai_search* sptr = search; sptr < search + search_count; ++sptr)
3372 // Check for IPv4 dotted decimal string.
3373 in4_addr_type inaddr;
3374 boost::system::error_code ec;
3375 if (socket_ops::inet_pton(BOOST_ASIO_OS_DEF(AF_INET),
3376 sptr->host, &inaddr, 0, ec) == 1)
3378 if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_UNSPEC)
3379 && hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET))
3381 freeaddrinfo_emulation(aihead);
3385 if (sptr->family == BOOST_ASIO_OS_DEF(AF_INET))
3387 rc = gai_aistruct(&ainext, &hints, &inaddr, BOOST_ASIO_OS_DEF(AF_INET));
3390 freeaddrinfo_emulation(aihead);
3398 // Check for IPv6 hex string.
3399 in6_addr_type in6addr;
3400 if (socket_ops::inet_pton(BOOST_ASIO_OS_DEF(AF_INET6),
3401 sptr->host, &in6addr, 0, ec) == 1)
3403 if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_UNSPEC)
3404 && hints.ai_family != BOOST_ASIO_OS_DEF(AF_INET6))
3406 freeaddrinfo_emulation(aihead);
3410 if (sptr->family == BOOST_ASIO_OS_DEF(AF_INET6))
3412 rc = gai_aistruct(&ainext, &hints, &in6addr,
3413 BOOST_ASIO_OS_DEF(AF_INET6));
3416 freeaddrinfo_emulation(aihead);
3424 // Look up hostname.
3426 char hbuf[8192] = "";
3427 hostent* hptr = socket_ops::gethostbyname(sptr->host,
3428 sptr->family, &hent, hbuf, sizeof(hbuf), hints.ai_flags, ec);
3431 if (search_count == 2)
3433 // Failure is OK if there are multiple searches.
3436 freeaddrinfo_emulation(aihead);
3438 if (ec == boost::asio::error::host_not_found)
3440 if (ec == boost::asio::error::host_not_found_try_again)
3442 if (ec == boost::asio::error::no_recovery)
3444 if (ec == boost::asio::error::no_data)
3449 // Check for address family mismatch if one was specified.
3450 if (hints.ai_family != BOOST_ASIO_OS_DEF(AF_UNSPEC)
3451 && hints.ai_family != hptr->h_addrtype)
3453 freeaddrinfo_emulation(aihead);
3455 socket_ops::freehostent(hptr);
3459 // Save canonical name first time.
3460 if (host != 0 && host[0] != '\0' && hptr->h_name && hptr->h_name[0]
3461 && (hints.ai_flags & AI_CANONNAME) && canon == 0)
3463 std::size_t canon_len = strlen(hptr->h_name) + 1;
3464 canon = gai_alloc<char>(canon_len);
3467 freeaddrinfo_emulation(aihead);
3468 socket_ops::freehostent(hptr);
3471 gai_strcpy(canon, hptr->h_name, canon_len);
3474 // Create an addrinfo structure for each returned address.
3475 for (char** ap = hptr->h_addr_list; *ap; ++ap)
3477 rc = gai_aistruct(&ainext, &hints, *ap, hptr->h_addrtype);
3480 freeaddrinfo_emulation(aihead);
3482 socket_ops::freehostent(hptr);
3487 socket_ops::freehostent(hptr);
3490 // Check if we found anything.
3497 // Return canonical name in first entry.
3498 if (host != 0 && host[0] != '\0' && (hints.ai_flags & AI_CANONNAME))
3502 aihead->ai_canonname = canon;
3507 std::size_t canonname_len = strlen(search[0].host) + 1;
3508 aihead->ai_canonname = gai_alloc<char>(canonname_len);
3509 if (aihead->ai_canonname == 0)
3511 freeaddrinfo_emulation(aihead);
3514 gai_strcpy(aihead->ai_canonname, search[0].host, canonname_len);
3519 // Process the service name.
3520 if (service != 0 && service[0] != '\0')
3522 rc = gai_serv(aihead, &hints, service);
3525 freeaddrinfo_emulation(aihead);
3530 // Return result to caller.
3535 inline boost::system::error_code getnameinfo_emulation(
3536 const socket_addr_type* sa, std::size_t salen, char* host,
3537 std::size_t hostlen, char* serv, std::size_t servlen, int flags,
3538 boost::system::error_code& ec)
3540 using namespace std;
3544 unsigned short port;
3545 switch (sa->sa_family)
3547 case BOOST_ASIO_OS_DEF(AF_INET):
3548 if (salen != sizeof(sockaddr_in4_type))
3550 return ec = boost::asio::error::invalid_argument;
3552 addr = reinterpret_cast<const char*>(
3553 &reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_addr);
3554 addr_len = sizeof(in4_addr_type);
3555 port = reinterpret_cast<const sockaddr_in4_type*>(sa)->sin_port;
3557 case BOOST_ASIO_OS_DEF(AF_INET6):
3558 if (salen != sizeof(sockaddr_in6_type))
3560 return ec = boost::asio::error::invalid_argument;
3562 addr = reinterpret_cast<const char*>(
3563 &reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_addr);
3564 addr_len = sizeof(in6_addr_type);
3565 port = reinterpret_cast<const sockaddr_in6_type*>(sa)->sin6_port;
3568 return ec = boost::asio::error::address_family_not_supported;
3571 if (host && hostlen > 0)
3573 if (flags & NI_NUMERICHOST)
3575 if (socket_ops::inet_ntop(sa->sa_family, addr, host, hostlen, 0, ec) == 0)
3583 char hbuf[8192] = "";
3584 hostent* hptr = socket_ops::gethostbyaddr(addr,
3585 static_cast<int>(addr_len), sa->sa_family,
3586 &hent, hbuf, sizeof(hbuf), ec);
3587 if (hptr && hptr->h_name && hptr->h_name[0] != '\0')
3589 if (flags & NI_NOFQDN)
3591 char* dot = strchr(hptr->h_name, '.');
3597 gai_strcpy(host, hptr->h_name, hostlen);
3598 socket_ops::freehostent(hptr);
3602 socket_ops::freehostent(hptr);
3603 if (flags & NI_NAMEREQD)
3605 return ec = boost::asio::error::host_not_found;
3607 if (socket_ops::inet_ntop(sa->sa_family,
3608 addr, host, hostlen, 0, ec) == 0)
3616 if (serv && servlen > 0)
3618 if (flags & NI_NUMERICSERV)
3622 return ec = boost::asio::error::no_buffer_space;
3624 #if defined(BOOST_ASIO_HAS_SECURE_RTL)
3625 sprintf_s(serv, servlen, "%u", ntohs(port));
3626 #else // defined(BOOST_ASIO_HAS_SECURE_RTL)
3627 sprintf(serv, "%u", ntohs(port));
3628 #endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
3632 #if defined(BOOST_ASIO_HAS_PTHREADS)
3633 static ::pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
3634 ::pthread_mutex_lock(&mutex);
3635 #endif // defined(BOOST_ASIO_HAS_PTHREADS)
3636 servent* sptr = ::getservbyport(port, (flags & NI_DGRAM) ? "udp" : 0);
3637 if (sptr && sptr->s_name && sptr->s_name[0] != '\0')
3639 gai_strcpy(serv, sptr->s_name, servlen);
3645 return ec = boost::asio::error::no_buffer_space;
3647 #if defined(BOOST_ASIO_HAS_SECURE_RTL)
3648 sprintf_s(serv, servlen, "%u", ntohs(port));
3649 #else // defined(BOOST_ASIO_HAS_SECURE_RTL)
3650 sprintf(serv, "%u", ntohs(port));
3651 #endif // defined(BOOST_ASIO_HAS_SECURE_RTL)
3653 #if defined(BOOST_ASIO_HAS_PTHREADS)
3654 ::pthread_mutex_unlock(&mutex);
3655 #endif // defined(BOOST_ASIO_HAS_PTHREADS)
3659 ec.assign(0, ec.category());
3663 #endif // !defined(BOOST_ASIO_HAS_GETADDRINFO)
3665 inline boost::system::error_code translate_addrinfo_error(int error)
3670 return boost::system::error_code();
3672 return boost::asio::error::host_not_found_try_again;
3674 return boost::asio::error::invalid_argument;
3676 return boost::asio::error::no_recovery;
3678 return boost::asio::error::address_family_not_supported;
3680 return boost::asio::error::no_memory;
3682 #if defined(EAI_ADDRFAMILY)
3683 case EAI_ADDRFAMILY:
3685 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
3688 return boost::asio::error::host_not_found;
3690 return boost::asio::error::service_not_found;
3692 return boost::asio::error::socket_type_not_supported;
3693 default: // Possibly the non-portable EAI_SYSTEM.
3694 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
3695 return boost::system::error_code(
3696 WSAGetLastError(), boost::asio::error::get_system_category());
3698 return boost::system::error_code(
3699 errno, boost::asio::error::get_system_category());
3704 boost::system::error_code getaddrinfo(const char* host,
3705 const char* service, const addrinfo_type& hints,
3706 addrinfo_type** result, boost::system::error_code& ec)
3708 host = (host && *host) ? host : 0;
3709 service = (service && *service) ? service : 0;
3711 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
3712 # if defined(BOOST_ASIO_HAS_GETADDRINFO)
3713 // Building for Windows XP, Windows Server 2003, or later.
3714 int error = ::getaddrinfo(host, service, &hints, result);
3715 return ec = translate_addrinfo_error(error);
3717 // Building for Windows 2000 or earlier.
3718 typedef int (WSAAPI *gai_t)(const char*,
3719 const char*, const addrinfo_type*, addrinfo_type**);
3720 if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
3722 if (gai_t gai = (gai_t)::GetProcAddress(winsock_module, "getaddrinfo"))
3724 int error = gai(host, service, &hints, result);
3725 return ec = translate_addrinfo_error(error);
3728 int error = getaddrinfo_emulation(host, service, &hints, result);
3729 return ec = translate_addrinfo_error(error);
3731 #elif !defined(BOOST_ASIO_HAS_GETADDRINFO)
3732 int error = getaddrinfo_emulation(host, service, &hints, result);
3733 return ec = translate_addrinfo_error(error);
3735 int error = ::getaddrinfo(host, service, &hints, result);
3736 #if defined(__MACH__) && defined(__APPLE__)
3737 using namespace std; // For isdigit and atoi.
3738 if (error == 0 && service && isdigit(static_cast<unsigned char>(service[0])))
3740 u_short_type port = host_to_network_short(atoi(service));
3741 for (addrinfo_type* ai = *result; ai; ai = ai->ai_next)
3743 switch (ai->ai_family)
3745 case BOOST_ASIO_OS_DEF(AF_INET):
3747 sockaddr_in4_type* sinptr =
3748 reinterpret_cast<sockaddr_in4_type*>(ai->ai_addr);
3749 if (sinptr->sin_port == 0)
3750 sinptr->sin_port = port;
3753 case BOOST_ASIO_OS_DEF(AF_INET6):
3755 sockaddr_in6_type* sin6ptr =
3756 reinterpret_cast<sockaddr_in6_type*>(ai->ai_addr);
3757 if (sin6ptr->sin6_port == 0)
3758 sin6ptr->sin6_port = port;
3767 return ec = translate_addrinfo_error(error);
3771 boost::system::error_code background_getaddrinfo(
3772 const weak_cancel_token_type& cancel_token, const char* host,
3773 const char* service, const addrinfo_type& hints,
3774 addrinfo_type** result, boost::system::error_code& ec)
3776 if (cancel_token.expired())
3777 ec = boost::asio::error::operation_aborted;
3779 socket_ops::getaddrinfo(host, service, hints, result, ec);
3783 void freeaddrinfo(addrinfo_type* ai)
3785 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
3786 # if defined(BOOST_ASIO_HAS_GETADDRINFO)
3787 // Building for Windows XP, Windows Server 2003, or later.
3790 // Building for Windows 2000 or earlier.
3791 typedef int (WSAAPI *fai_t)(addrinfo_type*);
3792 if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
3794 if (fai_t fai = (fai_t)::GetProcAddress(winsock_module, "freeaddrinfo"))
3800 freeaddrinfo_emulation(ai);
3802 #elif !defined(BOOST_ASIO_HAS_GETADDRINFO)
3803 freeaddrinfo_emulation(ai);
3809 boost::system::error_code getnameinfo(const socket_addr_type* addr,
3810 std::size_t addrlen, char* host, std::size_t hostlen,
3811 char* serv, std::size_t servlen, int flags, boost::system::error_code& ec)
3813 #if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
3814 # if defined(BOOST_ASIO_HAS_GETADDRINFO)
3815 // Building for Windows XP, Windows Server 2003, or later.
3817 int error = ::getnameinfo(addr, static_cast<socklen_t>(addrlen),
3818 host, static_cast<DWORD>(hostlen),
3819 serv, static_cast<DWORD>(servlen), flags);
3820 return ec = translate_addrinfo_error(error);
3822 // Building for Windows 2000 or earlier.
3823 typedef int (WSAAPI *gni_t)(const socket_addr_type*,
3824 int, char*, DWORD, char*, DWORD, int);
3825 if (HMODULE winsock_module = ::GetModuleHandleA("ws2_32"))
3827 if (gni_t gni = (gni_t)::GetProcAddress(winsock_module, "getnameinfo"))
3830 int error = gni(addr, static_cast<int>(addrlen),
3831 host, static_cast<DWORD>(hostlen),
3832 serv, static_cast<DWORD>(servlen), flags);
3833 return ec = translate_addrinfo_error(error);
3837 return getnameinfo_emulation(addr, addrlen,
3838 host, hostlen, serv, servlen, flags, ec);
3840 #elif !defined(BOOST_ASIO_HAS_GETADDRINFO)
3841 using namespace std; // For memcpy.
3842 sockaddr_storage_type tmp_addr;
3843 memcpy(&tmp_addr, addr, addrlen);
3844 addr = reinterpret_cast<socket_addr_type*>(&tmp_addr);
3846 return getnameinfo_emulation(addr, addrlen,
3847 host, hostlen, serv, servlen, flags, ec);
3850 int error = ::getnameinfo(addr, addrlen, host, hostlen, serv, servlen, flags);
3851 return ec = translate_addrinfo_error(error);
3855 boost::system::error_code sync_getnameinfo(
3856 const socket_addr_type* addr, std::size_t addrlen,
3857 char* host, std::size_t hostlen, char* serv,
3858 std::size_t servlen, int sock_type, boost::system::error_code& ec)
3860 // First try resolving with the service name. If that fails try resolving
3861 // but allow the service to be returned as a number.
3862 int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
3863 socket_ops::getnameinfo(addr, addrlen, host,
3864 hostlen, serv, servlen, flags, ec);
3867 socket_ops::getnameinfo(addr, addrlen, host, hostlen,
3868 serv, servlen, flags | NI_NUMERICSERV, ec);
3874 boost::system::error_code background_getnameinfo(
3875 const weak_cancel_token_type& cancel_token,
3876 const socket_addr_type* addr, std::size_t addrlen,
3877 char* host, std::size_t hostlen, char* serv,
3878 std::size_t servlen, int sock_type, boost::system::error_code& ec)
3880 if (cancel_token.expired())
3882 ec = boost::asio::error::operation_aborted;
3886 // First try resolving with the service name. If that fails try resolving
3887 // but allow the service to be returned as a number.
3888 int flags = (sock_type == SOCK_DGRAM) ? NI_DGRAM : 0;
3889 socket_ops::getnameinfo(addr, addrlen, host,
3890 hostlen, serv, servlen, flags, ec);
3893 socket_ops::getnameinfo(addr, addrlen, host, hostlen,
3894 serv, servlen, flags | NI_NUMERICSERV, ec);
3901 #endif // !defined(BOOST_ASIO_WINDOWS_RUNTIME)
3903 u_long_type network_to_host_long(u_long_type value)
3905 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
3906 unsigned char* value_p = reinterpret_cast<unsigned char*>(&value);
3907 u_long_type result = (static_cast<u_long_type>(value_p[0]) << 24)
3908 | (static_cast<u_long_type>(value_p[1]) << 16)
3909 | (static_cast<u_long_type>(value_p[2]) << 8)
3910 | static_cast<u_long_type>(value_p[3]);
3912 #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3913 return ntohl(value);
3914 #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3917 u_long_type host_to_network_long(u_long_type value)
3919 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
3921 unsigned char* result_p = reinterpret_cast<unsigned char*>(&result);
3922 result_p[0] = static_cast<unsigned char>((value >> 24) & 0xFF);
3923 result_p[1] = static_cast<unsigned char>((value >> 16) & 0xFF);
3924 result_p[2] = static_cast<unsigned char>((value >> 8) & 0xFF);
3925 result_p[3] = static_cast<unsigned char>(value & 0xFF);
3927 #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3928 return htonl(value);
3929 #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3932 u_short_type network_to_host_short(u_short_type value)
3934 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
3935 unsigned char* value_p = reinterpret_cast<unsigned char*>(&value);
3936 u_short_type result = (static_cast<u_short_type>(value_p[0]) << 8)
3937 | static_cast<u_short_type>(value_p[1]);
3939 #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3940 return ntohs(value);
3941 #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3944 u_short_type host_to_network_short(u_short_type value)
3946 #if defined(BOOST_ASIO_WINDOWS_RUNTIME)
3947 u_short_type result;
3948 unsigned char* result_p = reinterpret_cast<unsigned char*>(&result);
3949 result_p[0] = static_cast<unsigned char>((value >> 8) & 0xFF);
3950 result_p[1] = static_cast<unsigned char>(value & 0xFF);
3952 #else // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3953 return htons(value);
3954 #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME)
3957 } // namespace socket_ops
3958 } // namespace detail
3960 } // namespace boost
3962 #include <boost/asio/detail/pop_options.hpp>
3964 #endif // BOOST_ASIO_DETAIL_SOCKET_OPS_IPP