-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUdpClient.cpp
More file actions
64 lines (49 loc) · 1.96 KB
/
UdpClient.cpp
File metadata and controls
64 lines (49 loc) · 1.96 KB
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
53
54
55
56
57
58
59
60
61
62
#include "UdpClient.h"
#include <cstring>
#include <iostream>
#include <arpa/inet.h>
UdpClient::UdpClient(std::string ip) : ip(ip) {
this->port = "55533";
memset(&this->addr, 0, sizeof(this->addr));
this->addr.sin_family=AF_INET;
this->addr.sin_addr.s_addr=htonl(INADDR_ANY);
this->addr.sin_port=htons(0);
if((this->sock=socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return;
}
if(bind(this->sock,( struct sockaddr *) &this->addr, sizeof(this->addr)) < 0) {
return;
}
inet_pton(AF_INET, this->ip.c_str() , &this->addr.sin_addr.s_addr);
this->addr.sin_port = htons((uint16_t) std::stoi(this->port));
}
UdpClient::~UdpClient() {
}
void UdpClient::sendRequest(std::string request) const {
std::string first = to_10_digit_string(request.size());
if(first.size() != sendto(this->sock, first.c_str(), first.size(), 0,
(struct sockaddr *)&this->addr, sizeof(this->addr))) {
return;
}
if(request.size() != sendto(this->sock, request.c_str(), request.size(), 0,
(struct sockaddr *)&this->addr, sizeof(this->addr))) {
return;
}
std::cout<<"Sent request: "<<request.substr(0, 100) << "..." << std::endl << std::endl;
}
std::string UdpClient::getResponse() const {
int received(0);
int addrLength(sizeof(this->addr));
char buffer_size[10] = {0};
if(recvfrom(this->sock, buffer_size, 10, 0, (sockaddr *)&this->addr, (socklen_t*)&addrLength) != 10) {
perror("Mismatch in number of bytes received");
}
std::string bs(buffer_size);
int buff_size = std::stoi(bs);
std::string response(buff_size+1, 0);
if(recvfrom(this->sock, &response[0], buff_size, 0, (sockaddr *)&this->addr, (socklen_t*)&addrLength)!= buff_size) {
perror("Mismatch in number of bytes received");
}
std::cout<< "Received response: " << response.substr(0, 100) << "..." << std::endl << std::endl;
return response;
}