src/Socket.h
author František Kučera <franta-hg@frantovo.cz>
Tue, 26 Jul 2022 23:22:24 +0200
branchv_0
changeset 1 d93ea7346b66
parent 0 e8f15f432efc
child 2 2665ab0bcf44
permissions -rw-r--r--
first version: TCP-only + fixed parameters

/**
 * Relational pipes
 * Copyright © 2022 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once

#include <string>
#include <cstring>
#include <unistd.h>
#include <stdexcept>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

namespace relpipe {
namespace in {
namespace socket {

class Socket {
private:
	const static size_t MSG_SIZE = 8192; // TODO: configurable/dynamic

public:

	virtual ~Socket() {
	}

	std::string receive() {
		char buffer[MSG_SIZE + 1];
		memset(buffer, 0, MSG_SIZE + 1);

		int s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

		struct sockaddr_in a;
		memset((char *) &a, 0, sizeof (a));
		a.sin_family = AF_INET;
		a.sin_addr.s_addr = inet_addr("127.0.0.1"); // TODO: use getaddrinfo() instead (because of error -1 = 255.255.255.255)
		a.sin_port = htons(1234);
		::bind(s, (sockaddr*) & a, sizeof (a));

		struct sockaddr_in remoteAddress;
		memset((char *) &remoteAddress, 0, sizeof (remoteAddress));
		socklen_t remoteAddressSize = sizeof(remoteAddress);

		ssize_t msgSize = recvfrom(s, buffer, sizeof (buffer), 0, (sockaddr*) & remoteAddress, &remoteAddressSize);

		close(s);

		if (msgSize > sizeof (buffer))throw std::logic_error("Invalid Socket message size.");
		else if (msgSize >= 0) return std::string(buffer, msgSize);
		else throw std::logic_error("Unable to receive Socket message the socket; error: " + std::string(strerror(errno)));
	}

};

}
}
}