Socket.cpp 2.16 KB
Newer Older
/jdi/'s avatar
/jdi/ committed
1
2
3
4
5
6
7
8
9
10
/*
 * Socket.cpp
 *
 *  Created on: 02.09.2015
 *      Author: jdi
 */
#include <cstdio>
#include <cerrno>
#include <cstring>
#include <cstdlib>
/jdi/'s avatar
/jdi/ committed
11
#include <array>
/jdi/'s avatar
/jdi/ committed
12
13
14
15
16
17
18
19
20
21
#include <unistd.h>
#include <asio.hpp>
#include "Socket.h"
#include "Packet.h"
#include "Types.h"
#include "Utils.h"
#include "Options.h"
#include "Host.h"

Socket::Socket(asio::io_service& io_service) :
/jdi/'s avatar
/jdi/ committed
22
		send_socket_(io_service), receive_socket_(io_service) {
/jdi/'s avatar
/jdi/ committed
23
}
/jdi/'s avatar
/jdi/ committed
24
//, resolver(				io_service)
/jdi/'s avatar
/jdi/ committed
25
26
27
28
29
30
31
32
void Socket::init(short dst_port, short src_port) {

	if (options.flags & FLAG_REVERSE) {
		short p = dst_port;
		dst_port = src_port;
		src_port = p;
	}

/jdi/'s avatar
/jdi/ committed
33
34
35
36
	printf("IP:\t");
	utils::printDec(local_ip);
	printf("\n");

/jdi/'s avatar
/jdi/ committed
37
	wildcard_endpoint_ = asio::ip::udp::endpoint(
/jdi/'s avatar
/jdi/ committed
38
			asio::ip::address_v4::from_string("0.0.0.0"), src_port);
/jdi/'s avatar
/jdi/ committed
39
	local_endpoint_ = asio::ip::udp::endpoint(asio::ip::address_v4(local_ip),
/jdi/'s avatar
/jdi/ committed
40
			src_port);
/jdi/'s avatar
/jdi/ committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
	broadcast_endpoint_ = asio::ip::udp::endpoint(
			asio::ip::address_v4::from_string("255.255.255.255"), dst_port);

	send_socket_.open(asio::ip::udp::v4());
	send_socket_.set_option(asio::socket_base::broadcast(true));
	send_socket_.set_option(asio::socket_base::reuse_address(true));
	send_socket_.bind(local_endpoint_); //TODO reuse Address

	receive_socket_.open(asio::ip::udp::v4());
	receive_socket_.set_option(asio::socket_base::broadcast(true));
	receive_socket_.set_option(asio::socket_base::reuse_address(true));
	receive_socket_.bind(wildcard_endpoint_); //TODO reuse Address

}

/jdi/'s avatar
/jdi/ committed
56
57
58
59
void Socket::setHostIp(bytes ip) {
	local_ip=ip;
}

/jdi/'s avatar
/jdi/ committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
void Socket::send(bytes data) {
	unsigned char * a = &data[0];
	send_socket_.async_send_to(asio::buffer(a, data.size()),
			broadcast_endpoint_,
			[this](asio::error_code ec, std::size_t bytes_sent)
			{
				listen();
			});
}

void Socket::listen() {
	data.resize(MAX_LENGTH);
	receive_socket_.async_receive_from(asio::buffer(data, MAX_LENGTH),
			remote_endpoint_,
			[this](asio::error_code ec, std::size_t bytes_recvd)
			{
				if (ec || bytes_recvd == 0) {
					listen();
				} else {
					data.resize(bytes_recvd);
					Packet p = Packet(Packet::READ);
					p.encode(data);
					p.parse(data);
					datasets l = p.getPayload();
					if(!callback(p)) {
						listen();
					}
				}
			});
}