owlps/infrastructure-centred/libowlps-client/libowlps-client.c

99 lines
2.6 KiB
C

#include "owlps-client.h"
#define DEBUG
/*
* Opens an UDP socket to the aggregator (whose IP address is 'dest_ip'
* and listening port is 'dest_port'). The server information is stored
* into 'server'. The socket will send through the network interface
* 'iface' if specified (if you want the interface to be selected,
* automatically, this parameter should be NULL or an empty string).
*/
int owlps_create_socket_to_aggregator(char *dest_ip,
uint_fast16_t dest_port,
struct sockaddr_in *server,
char *iface)
{
struct sockaddr_in client ;
int sockfd = create_udp_sending_socket(dest_ip, dest_port,
server, &client) ;
if (sockfd < 0)
{
perror("Error! Cannot create UDP sending socket to the aggregation"
" server") ;
exit(ERR_CREATING_SOCKET) ;
}
// If we specified an interface name
if (iface != NULL && iface[0] != '\0')
owlps_use_iface(sockfd, iface) ;
return sockfd ;
}
/* Selects 'iface' as sending interface for the socket 'sockfd'. */
void owlps_use_iface(int sockfd, char *iface)
{
if (setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, iface,
strlen(iface) + 1) == -1)
{
fprintf(stderr, "Error! Cannot select interface %s to send the"
" packet: ", iface) ;
perror("") ;
fprintf(stderr, "Sending through the default interface.\n") ;
}
}
void owlps_send_request(int sockfd, struct sockaddr_in *server,
void *packet, uint_fast16_t packet_size,
uint_fast16_t nb_pkt, uint_fast32_t delay)
{
uint_fast16_t i ;
#ifdef DEBUG
printf("Sent packets: ") ;
#endif // DEBUG
// Transmit first packet:
owlps_send_packet(sockfd, server, packet, packet_size) ;
// Transmit remaining packets (if any):
for (i = 0 ; i < nb_pkt - 1 ; ++i)
{
usleep(delay) ; // Wait during the wanted delay
owlps_send_packet(sockfd, server, packet, packet_size) ;
}
#ifdef DEBUG
putchar('\n') ;
#endif // DEBUG
}
void owlps_send_packet(int sockfd, struct sockaddr_in *server,
void *packet, uint_fast16_t packet_size)
{
ssize_t nsent = sendto(sockfd, packet, packet_size, 0,
(struct sockaddr *) server,
(socklen_t) sizeof(*server)) ;
if (nsent != (ssize_t) packet_size)
{
perror("Error sending data to the aggregation server") ;
exit(ERR_SENDING_INFO) ;
}
#ifdef DEBUG
putchar('.') ;
fflush(stdout) ;
#endif // DEBUG
}