udp6echo.cpp 1.28 KB
#include <iostream>
#include <string>
#include "sockpp/udp6_socket.h"
#include "sockpp/version.h"

using namespace std;

// --------------------------------------------------------------------------

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

	string host = (argc > 1) ? argv[1] : "localhost";
	in_port_t port = (argc > 2) ? atoi(argv[2]) : 12345;

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

	osdev::components::socket-cpp::udp6_socket sock;

	if (!sock.connect(osdev::components::socket-cpp::inet6_address(host, port))) {
		cerr << "Error connecting to server at " << host << ":" << port 
			<< "\n\t" << sock.last_error_str() << endl;
		return 1;
	}

	cout << "Created UDP socket at: " << sock.address() << endl;

	string s, sret;
	while (getline(cin, s) && !s.empty()) {
		if (sock.send(s) != ssize_t(s.length())) {
			cerr << "Error writing to the UDP socket: "
				<< sock.last_error_str() << endl;
			break;
		}

		sret.resize(s.length());
		ssize_t n = sock.recv(&sret[0], s.length());

		if (n != ssize_t(s.length())) {
			cerr << "Error reading from UDP socket: "
				<< sock.last_error_str() << endl;
			break;
		}

		cout << sret << endl;
	}

	return (!sock) ? 1 : 0;
}