78 lines
2.3 KiB
C
78 lines
2.3 KiB
C
#include "dht.h"
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <netdb.h>
|
|
#include <netinet/in.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
|
|
// #define cpy(x, y, z) char *x_c = x; char *y_c = y; while(*y_c && z--) *x_c++ = *y_c++
|
|
|
|
void build_lookup_request(lookup_request* lr){
|
|
char *lrreq = lr->node_request;
|
|
snprintf(lr->node_request, HTTP_MAX_SIZE, "%d|%hd|%d|%s|%d\r\n\r\n", lr->message_type, lr->hash_id, lr->node_id, lr->node_ip, lr->node_port);
|
|
}
|
|
|
|
void lookup_request_init(lookup_request* lr, int message_type, int node_id, char *node_ip, int node_port, uint16_t hash_id, char *node_request)
|
|
{
|
|
lr->message_type = message_type;
|
|
lr->node_id = node_id;
|
|
strncpy(lr->node_ip, node_ip, NODE_IP_MAX_SIZE);
|
|
lr->node_port = node_port;
|
|
lr->hash_id = hash_id;
|
|
if(node_request != NULL)
|
|
strncpy(lr->node_request, node_request, HTTP_MAX_SIZE);
|
|
build_lookup_request(lr);
|
|
}
|
|
|
|
void extract_lookup_request(lookup_request* lr, char* request){
|
|
sscanf(request, "%d|%hd|%d|%s|%d\r\n\r\n", &lr->message_type, &lr->hash_id, &lr->node_id, lr->node_ip, &lr->node_port);
|
|
}
|
|
|
|
int call_network(lookup_request* lr, char *ip, int port){
|
|
int succ_sock;
|
|
struct addrinfo hints, *servinfo, *p;
|
|
int rv;
|
|
int numbytes;
|
|
|
|
memset(&hints, 0, sizeof hints);
|
|
hints.ai_family = AF_INET;
|
|
hints.ai_socktype = SOCK_DGRAM;
|
|
|
|
char port_str[6];
|
|
snprintf(port_str, sizeof port_str, "%d", port);
|
|
|
|
if ((rv = getaddrinfo(ip, port_str, &hints, &servinfo)) != 0) {
|
|
fprintf(stderr, "Func: call_network - getaddrinfo: %s\n", gai_strerror(rv));
|
|
return 1;
|
|
}
|
|
|
|
for(p = servinfo; p != NULL; p = p->ai_next) {
|
|
if ((succ_sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
|
|
perror("Func: call_network - socket");
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
|
|
if (p == NULL) {
|
|
fprintf(stderr, "Func: call_network - failed to create socket\n");
|
|
return 2;
|
|
}
|
|
|
|
if ((numbytes = sendto(succ_sock, lr->node_request, strlen(lr->node_request), 0, p->ai_addr, p->ai_addrlen)) == -1) {
|
|
perror("Func: call_network - sendto");
|
|
exit(1);
|
|
}
|
|
|
|
freeaddrinfo(servinfo);
|
|
close(succ_sock);
|
|
|
|
return 0;
|
|
}
|
|
|
|
void clone_lookup_request(lookup_request* dest, lookup_request* source){
|
|
memcpy(dest, source, sizeof(lookup_request));
|
|
}
|