Files
ft_ping/srcs/ft_ping.c

119 lines
3.4 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_ping.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tomoron <tomoron@student.42angouleme.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/04/26 19:54:25 by tomoron #+# #+# */
/* Updated: 2025/08/22 15:45:44 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", host, set->current_ip);
if(set->verbose)
printf(", id 0x%04x = %d", set->id, set->id);
printf("\n");
}
void ping_end_print(t_settings *set, char *host, t_stats *stats)
{
int percent;
double stddev;
if(set->err)
return;
(void)set;
stddev = sqrt(stats->sqr_diff / (stats->received - 1));
if(isnan(stddev) || isinf(stddev))
stddev = 0.0f;
printf("--- %s ping statistics ---\n", host);
if(stats->sent)
percent = ((double)(stats->sent - stats->received) / stats->sent) * 100.0;
else
percent = 0;
printf("%lu packets transmitted, %lu packets received, %d%% packet loss\n", stats->sent, stats->received, percent);
if(stats->received)
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 == 0) && !g_stop)
{
tmp = send_icmp(set, info, &seq, &last_sent, &stats);
if(tmp)
waitlist_add(&wl, tmp);
usleep(100);
receive_icmp(set, &wl, &stats);
}
while(wl && !g_stop && timediff(&set->last_send_time) < set->linger)
receive_icmp(set, &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;
if(set->setTtl)
setsockopt(set->socket, IPPROTO_IP, IP_TTL, &set->ttl, sizeof(set->ttl));
while(cur)
{
if(!ping_host(set, cur->host))
return;
cur = cur->next;
}
}