src/Socket.h
author František Kučera <franta-hg@frantovo.cz>
Sun, 07 Aug 2022 10:45:05 +0200
branchv_0
changeset 2 2665ab0bcf44
parent 1 d93ea7346b66
child 3 2b57c8683ffe
permissions -rw-r--r--
reuse the UDP socket

/**
 * 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
	int s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

public:

	Socket() {
		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));

		// int soBufferSize = 1024 * 1024;
		// setsockopt(s, SOL_SOCKET, SO_RCVBUF, &soBufferSize, sizeof (soBufferSize));
		// soBufferSize = 0;
		// socklen_t soBufferSizeLength = sizeof (soBufferSize);

		// std::cerr << "soBufferSize=" << soBufferSize << std::endl;
		// getsockopt(s, SOL_SOCKET, SO_RCVBUF, &soBufferSize, &soBufferSizeLength);
		// std::cerr << "soBufferSize=" << soBufferSize << " length=" << soBufferSizeLength << std::endl;
	}

	virtual ~Socket() {
		close(s);
	}

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

		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);


		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)));
	}

};

}
}
}