diff --git a/.vscode/settings.json b/.vscode/settings.json index 70e34ec..158e92b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,6 @@ { - "C_Cpp.errorSquiggles": "disabled" + "C_Cpp.errorSquiggles": "disabled", + "files.associations": { + "ip.h": "c" + } } \ No newline at end of file diff --git a/srcs/main.c b/srcs/main.c index 5461b49..9420e62 100644 --- a/srcs/main.c +++ b/srcs/main.c @@ -142,6 +142,31 @@ double nsqrt(double a, double prec) { return c; } +void print_ip_hdr(int verbose, struct ip* ip_header) { + if (verbose) { + printf("IP Hdr dump:\n "); + for (size_t i = 0; i < sizeof(*ip_header); i++) { + printf("%02x", *((unsigned char*)ip_header + i)); + if (i % 2) { + printf(" "); + } + } + printf("\n"); + } + + printf("Vr HL TOS Len ID Flg off TTL Pro cks Src\tDst\tData\n"); + printf(" %1x %1x %02x %04x %04x %1x %04x %02x %02x %04x %s %s ", ip_header->ip_v, ip_header->ip_hl, + ip_header->ip_tos, (ip_header->ip_len > 0x2000) ? ntohs(ip_header->ip_len) : ip_header->ip_len, + ntohs(ip_header->ip_id), (ntohs(ip_header->ip_off) & 0xe000) >> 13, ntohs(ip_header->ip_off) & 0x1fff, + ip_header->ip_ttl, ip_header->ip_p, ntohs(ip_header->ip_sum), + inet_ntoa(*((struct in_addr*)&ip_header->ip_src)), inet_ntoa(*((struct in_addr*)&ip_header->ip_dst))); + unsigned char* cp = (unsigned char*)ip_header + sizeof(*ip_header); + for (size_t l = ip_header->ip_hl << 2; l > sizeof(*ip_header); l--) { + printf("%02x", *cp++); + } + printf("\n"); +} + int main(int argc, char** argv) { struct arguments arguments; int timeout = 3000; @@ -223,6 +248,9 @@ int main(int argc, char** argv) { send_ping(); + struct sockaddr_in localhost; + inet_pton(AF_INET, "127.0.0.1", &(localhost.sin_addr)); + while (!stop) { int ret = poll(fds, 1, timeout); if (ret > 0) { @@ -250,7 +278,10 @@ int main(int argc, char** argv) { char strip[INET_ADDRSTRLEN] = {0}; inet_ntop(AF_INET, &(ip_header->ip_src.s_addr), strip, INET_ADDRSTRLEN); struct icmphdr* icmp_reply = (struct icmphdr*)(buf + (ip_header->ip_hl << 2)); - if (icmp_reply->type == 0) { + if (icmp_reply->type == ICMP_ECHO && ip_header->ip_src.s_addr == localhost.sin_addr.s_addr) { + continue; + } else if (icmp_reply->type != ICMP_ECHOREPLY) { + print_ip_hdr(arguments.verbose, ip_header); continue; } @@ -271,8 +302,9 @@ int main(int argc, char** argv) { ((recvt.tv_sec * 1000 + recvt.tv_nsec / 1000000) - (sendt.tv_sec * 1000 + sendt.tv_nsec / 1000000)); tmp += ((double)((recvt.tv_nsec - sendt.tv_nsec) % 1000000) / 1000000.0); - printf("%zd bytes from %s: icmp_seq=%d ttl=%d time=%.3f ms \n", bytes_received - sizeof(struct ip), - strip, icmp_reply->un.echo.sequence, ip_header->ip_ttl, tmp); + printf("%zd bytes from %s: icmp_seq=%d ttl=%d time=%.3f ms %s\n", bytes_received - sizeof(struct ip), + strip, icmp_reply->un.echo.sequence, ip_header->ip_ttl, tmp, + icmp_reply->un.echo.sequence < xmit ? "" : " (DUP!)"); min = (((min) < (tmp)) ? (min) : (tmp)); max = (((max) > (tmp)) ? (max) : (tmp));