Skip to content

Instantly share code, notes, and snippets.

@blakejohnson
Created May 12, 2017 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blakejohnson/ee5221b9c872d6a746fe7508e55bd1b1 to your computer and use it in GitHub Desktop.
Save blakejohnson/ee5221b9c872d6a746fe7508e55bd1b1 to your computer and use it in GitHub Desktop.
asio-based "socketpair" for Win32
#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