summaryrefslogtreecommitdiff
path: root/include/net/client.hpp
blob: 23d250b7235f9df974b8c6571a7b5d355f390e8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma once

#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <string>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>

#include "net/conn.hpp"

namespace net {

class client {
	struct sockaddr_in server_address { };

public:
	client(std::string hostname, int port)
	{
		server_address.sin_family = AF_INET;
		inet_pton(AF_INET, hostname.c_str(), &server_address.sin_addr);
		server_address.sin_port = htons(port);
	}

	conn connect()
	{
		int sock_fd;

		sock_fd = socket(AF_INET, SOCK_STREAM, 0);
		if (sock_fd < 0)
			throw std::runtime_error(strerror(errno));

		auto err = ::connect(sock_fd, (struct sockaddr*)&server_address,
		    sizeof(server_address));
		if (err < 0)
			throw std::runtime_error(strerror(errno));

		return conn { sock_fd, server_address, sizeof(server_address) };
	}
};
};