undgramechosvr.cpp 1.23 KB
#include <iostream>
#include "socket-cpp/unix_dgram_socket.h"
#include "socket-cpp/version.h"

using namespace std;

// --------------------------------------------------------------------------
// The main thread creates the UDP socket, and then starts them running the
// echo service in a loop.

int main(int argc, char* argv[])
{
	cout << "Sample Unix-domain datagram echo server for 'sockpp' "
		<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;

	osdev::components::socket-cpp::socket_initializer sockInit;

	osdev::components::socket-cpp::unix_dgram_socket sock;
	if (!sock) {
		cerr << "Error creating the socket: " << sock.last_error_str() << endl;
		return 1;
	}

	if (!sock.bind(osdev::components::socket-cpp::unix_address("/tmp/undgramechosvr.sock"))) {
		cerr << "Error binding the socket: " << sock.last_error_str() << endl;
		return 1;
	}

	// Run the socket in this thread.
	ssize_t n;
	char buf[512];

	osdev::components::socket-cpp::unix_address srcAddr;

	cout << "Awaiting packets on: '" << sock.address() << "'" << endl;

	// Read some data, also getting the address of the sender,
	// then just send it back.
	while ((n = sock.recv_from(buf, sizeof(buf), &srcAddr)) > 0)
		sock.send_to(buf, n, srcAddr);

	return 0;
}