106 lines
3.0 KiB
C
106 lines
3.0 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_ping.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: tomoron <tomoron@student.42angouleme.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2025/04/26 19:54:25 by tomoron #+# #+# */
|
|
/* Updated: 2025/05/02 01:04:29 by tomoron ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "includes/ft_ping.h"
|
|
|
|
struct addrinfo *resolve_ip(char *host, t_settings *settings)
|
|
{
|
|
struct addrinfo hints, *result;
|
|
int s;
|
|
struct addrinfo *ret;
|
|
|
|
memset(&hints, 0, sizeof(hints));
|
|
ret = 0;
|
|
hints.ai_family = AF_INET;
|
|
hints.ai_socktype = SOCK_STREAM;
|
|
|
|
s = getaddrinfo(host, NULL, &hints, &result);
|
|
if (s != 0) {
|
|
fprintf(stderr, "%s: %s\n",settings->name, gai_strerror(s));
|
|
return(ret);
|
|
}
|
|
|
|
ret = result;
|
|
if(!ret)
|
|
return(ret);
|
|
ret->ai_next = 0;
|
|
result = result->ai_next;
|
|
freeaddrinfo(result);
|
|
return(ret);
|
|
}
|
|
|
|
void ping_start_print(t_settings *set, char *host)
|
|
{
|
|
printf("PING %s (%s): 56 data bytes\n", host, set->current_ip);
|
|
}
|
|
|
|
void ping_end_print(t_settings *set, char *host, t_stats *stats)
|
|
{
|
|
int percent;
|
|
double stddev;
|
|
|
|
(void)set;
|
|
stddev = sqrt(stats->sqr_diff / (stats->received - 1));
|
|
printf("--- %s ping statistics ---\n", host);
|
|
percent = ((double)stats->sent / 100) * stats->received;
|
|
printf("%lu packets transmitted, %lu packets received, %d%% packet loss\n", stats->sent, stats->received, percent);
|
|
printf("round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\n", stats->min, stats->avg, stats->max, stddev);
|
|
}
|
|
|
|
int ping_host(t_settings *set, char *host)
|
|
{
|
|
uint16_t seq;
|
|
struct addrinfo *info;
|
|
struct timeval last_sent;
|
|
t_waitlist *wl;
|
|
t_waitlist *tmp;
|
|
t_stats stats;
|
|
|
|
seq = 0;
|
|
memset(&stats, 0, sizeof(t_stats));
|
|
info = resolve_ip(host, set);
|
|
if(!info)
|
|
return(0);
|
|
last_sent.tv_sec = 0;
|
|
last_sent.tv_usec = 0;
|
|
wl = 0;
|
|
inet_ntop(info->ai_family, (void *)&((struct sockaddr_in *)(info->ai_addr))->sin_addr, set->current_ip, sizeof(set->current_ip));
|
|
ping_start_print(set, host);
|
|
while((seq < set->count || set->count == -1) && !g_stop)
|
|
{
|
|
tmp = send_icmp(set, info, &seq, &last_sent, &stats);
|
|
if(tmp)
|
|
waitlist_add(&wl, tmp);
|
|
usleep(100);
|
|
receive_icmp(set, info, &wl, &stats);
|
|
}
|
|
while(wl && !g_stop)
|
|
receive_icmp(set, info, &wl, &stats);
|
|
ping_end_print(set, host, &stats);
|
|
freeaddrinfo(info);
|
|
waitlist_free(wl);
|
|
return(1);
|
|
}
|
|
|
|
void send_pings(t_settings *set)
|
|
{
|
|
t_host_list *cur;
|
|
|
|
cur = set->hosts;
|
|
while(cur)
|
|
{
|
|
if(!ping_host(set, cur->host))
|
|
return;
|
|
cur = cur->next;
|
|
}
|
|
}
|