CLI
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

49 lines
1.4 KiB

#include "udpclient.hpp"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sstream>
UDPClient::UDPClient(const std::string& addr, int port)
: addr(addr), port(port) {
createSocket();
}
UDPClient::UDPClient(const std::string& addr) {
if (addr.find(':') <= addr.length()) {
std::string ip = addr.substr(0, addr.find(":"));
std::string port = addr.substr(addr.find(":") + 1, addr.length());
int portnum = -1;
std::stringstream ss;
ss << port;
ss >> portnum;
this->port = portnum;
this->addr = ip;
} else {
this->addr = addr;
this->port = DEF_PORT;
}
createSocket();
}
void UDPClient::createSocket() {
if ((clientsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
}
void UDPClient::requestInfo(const std::string& hash) {
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(port);
inet_pton(AF_INET, addr.c_str(), &(serveraddr.sin_addr));
FileInfoPacket fip;
fip.identifier = p_identifier_req;
memcpy(fip.file_hash, hash.c_str(), hash.length());
sendto(clientsocket, &fip, sizeof(fip), MSG_CONFIRM,
(const struct sockaddr*)&serveraddr, sizeof(serveraddr));
}