check/add/update neighbours

This commit is contained in:
gonzalef 2020-04-24 20:23:57 +02:00
parent 543a2a266e
commit c633955b54
2 changed files with 69 additions and 1 deletions

View File

@ -51,6 +51,63 @@ neighbour_peer *get_random_neighbour() {
return (neighbour_peer*) tmp->data;
}
// Search for this peer in the neighbour table
neighbour_peer *get_neighbour(struct in6_addr *ip) {
// Look for neighbour
list *tmp = neighbour_list;
neighbour_peer *peer;
while(tmp != NULL) {
// check for same ip and same port
peer = (neighbour_peer*) tmp->data;
if(memcmp(&peer->ip, ip, sizeof(struct in6_addr)) == 0)
return peer;
// if they differ, get next peer
tmp = tmp->next;
}
return NULL;
}
// Return -1 if the peer could not be added, 0 if it could or if it was already in the table
int add_n_update_neighbour(struct in6_addr *ip) {
neighbour_peer *peer = get_neighbour(ip);
struct timeval curtime;
// peer is not in the neighbour list so we try to add it
if(ip == NULL) {
// check if there are less than 15 neighbours
if(len_list(neighbour_list) == 15)
return -1;
// if there are less, initialize the new peer to add to the list
peer = (neighbour_peer*) malloc(sizeof(neighbour_peer));
memcpy(&peer->ip, ip, sizeof(struct in6_addr));
peer->port = LISTEN_PORT;
peer->is_temporary = 1;
// set last_seen time
gettimeofday(&curtime, NULL);
memcpy(&peer->last_seen, &curtime, sizeof(struct timeval));
// set new peer as head of list
list *node = (list*) malloc(sizeof(list));
node->data = (void*) peer;
node->next = neighbour_list;
neighbour_list = node;
return 0;
}
// if the peer was already in the list, update it
gettimeofday(&curtime, NULL);
memcpy(&peer->last_seen, &curtime, sizeof(struct timeval));
return 0;
}
// get data associated with id, if it doesn't exist return NULL
pub_data *get_data(int64_t id) {
list *tmp = data_list;
@ -702,7 +759,11 @@ int listen_for_packets(char * received_data_buffer, int received_data_len, struc
return -1;
}
// TODO : Add the neighbour check here.
// Neighbour check
if(add_n_update_neighbour(sender) == -1) {
fprintf(stderr, ">> Maximum number of neighbour peers reached, aborting this packet.\n");
return -1;
}
// struct tlv_list received_tlvs;
// if (validate_tlvs(formated_rec_datagram) < 0)

View File

@ -10,6 +10,7 @@
#include <netinet/in.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#include <net/if.h>
@ -121,6 +122,12 @@ int len_list(list *l);
neighbour_peer *get_random_neighbour();
// Search for this peer in the neighbour table
neighbour_peer *get_neighbour(struct in6_addr *ip);
// Return -1 if the peer could not be added, 0 if it could or if it was already in the table
int add_n_update_neighbour(struct in6_addr *ip);
// get data associated with id, if it doesn't exist return NULL
pub_data *get_data(int64_t id);