aboutsummaryrefslogtreecommitdiffstats
path: root/c/ping.c
blob: 8671318c36d6eb1d4dd5e92590b9986f10a606c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "resolve.h"
/* ping HOST|IP - originate ICMP echo requests via the kernel socket layer.
   Resolves a hostname via DNS first (resolve.h); default target 10.0.0.1. No
   SLIP/IP/checksums here - the kernel owns all of that. */

/* rbuf is first + large so namebuf/dst land past the arg string at 0xA000 */
static unsigned char rbuf[96];
static unsigned char namebuf[64];
static unsigned char dst[4];
static unsigned char payload[4];

static void put_ip(unsigned char *ip) {
    unsigned char i;
    for (i = 0; i < 4; i++) { putu(ip[i]); if (i < 3) putc('.'); }
}

/* wait up to ~2s for an echo reply without blocking in the kernel: a lost
   reply (some hosts rate-limit ICMP) must cost one "timeout" line, not
   minutes wedged inside net_recv's pump-counted wait. */
static unsigned char wait_reply(unsigned char s) {
    unsigned char t, r;
    for (t = 0; t < 40; t++) {
        r = net_recv_nb(s, rbuf, (unsigned char)sizeof(rbuf));
        if (r != 0xFE) return r;       /* reply (or error) */
        msleep(50);
    }
    return 0xFF;                       /* ~2s with no reply */
}

void main(void) {
    char *arg;
    unsigned char s, seq, got = 0, i;
    arg = getargs();
    if (!arg || !*arg) { dst[0] = 10; dst[1] = 0; dst[2] = 0; dst[3] = 1; }
    else {
        for (i = 0; arg[i] && i < 63; i++) namebuf[i] = (unsigned char)arg[i];
        namebuf[i] = 0;
        if (!resolve((char *)namebuf, dst)) {
            puts("ping: cannot resolve "); puts((char *)namebuf); nl(); sexit(1);
        }
    }

    payload[0] = 'g'; payload[1] = 'b'; payload[2] = 'o'; payload[3] = 's';
    s = net_socket(SOCK_ICMP);
    if (s == 0xFF) { puts("ping: no socket"); nl(); sexit(1); }
    net_connect(s, dst, 0);

    puts("PING "); put_ip(dst); nl();
    for (seq = 1; seq <= 4; seq++) {
        net_send(s, payload, 4);
        if (wait_reply(s) != 0xFF) {
            got++;
            puts("  reply from "); put_ip(dst); puts(" seq="); putu(seq); nl();
        } else {
            puts("  seq="); putu(seq); puts(" timeout"); nl();
        }
        if (seq < 4) msleep(800);      /* pace like real ping */
    }
    puts("-- "); putu(got); puts("/4 received"); nl();
    net_close(s);
}