Created
May 12, 2017 15:44
-
-
Save blakejohnson/ee5221b9c872d6a746fe7508e55bd1b1 to your computer and use it in GitHub Desktop.
asio-based "socketpair" for Win32
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdint> | |
#include "asio.hpp" | |
using namespace std; | |
using asio::ip::tcp; | |
void my_socketpair(asio::io_service &ios, tcp::socket &s1, tcp::socket &s2) { | |
// uses a strategy cribbed from Cygwin to mimick a posix socket pair on win32 | |
try { | |
// open a listener and let the OS choose a port | |
tcp::acceptor acceptor(ios, tcp::endpoint(asio::ip::address_v4::loopback(), 0)); | |
// read off what port the OS gave us | |
uint16_t port = acceptor.local_endpoint().port(); | |
// connect to that port | |
s1.connect(tcp::endpoint(asio::ip::address_v4::loopback(), port)); | |
// accept the connection on the second socket | |
acceptor.accept(s2); | |
// close the acceptor | |
acceptor.close(); | |
} catch (exception &e) { | |
cerr << "Socket error: " << e.what() << endl; | |
s1.close(); | |
s2.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment