blob: 36435d454b8de0cc166faabcf2dae044ae09ef03 (
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
|
#include "netlib.h"
/* netd - a minimal IP stack over SLIP. Milestone A: answer ICMP echo (ping).
Our address is 10.0.0.2; the SLIP peer (gateway) is 10.0.0.1.
Everything is done on raw byte arrays so endianness is explicit (network
byte order = big-endian): field[hi], field[lo]. */
/* Internet checksum (RFC 1071): 16-bit one's-complement sum with carry fold. */
static unsigned int cksum(unsigned char *d, unsigned char len) {
unsigned int sum = 0, w;
unsigned char i = 0;
while ((unsigned char)(i + 1) < len) {
w = ((unsigned int)d[i] << 8) | d[i + 1];
sum += w; if (sum < w) sum++;
i += 2;
}
if (len & 1) { w = (unsigned int)d[len - 1] << 8; sum += w; if (sum < w) sum++; }
return ~sum;
}
void main(void) {
unsigned char pkt[128];
unsigned char len, ihl, i, t;
unsigned int c;
puts("netd: IP/ICMP up (10.0.0.2)"); nl();
for (;;) {
len = slip_recv((char *)pkt, 127);
if (len < 28) continue; /* IP(20) + ICMP(8) minimum */
if ((pkt[0] >> 4) != 4) continue; /* IPv4 only */
ihl = (pkt[0] & 0x0f) << 2;
if (pkt[9] != 1) continue; /* protocol 1 = ICMP */
if (pkt[ihl] != 8) continue; /* ICMP type 8 = echo request */
/* turn the request into a reply, in place */
for (i = 0; i < 4; i++) { t = pkt[12 + i]; pkt[12 + i] = pkt[16 + i]; pkt[16 + i] = t; }
pkt[8] = 64; /* reset TTL */
pkt[ihl] = 0; /* ICMP type -> echo reply */
pkt[ihl + 2] = 0; pkt[ihl + 3] = 0; /* recompute ICMP checksum */
c = cksum(pkt + ihl, (unsigned char)(len - ihl));
pkt[ihl + 2] = (unsigned char)(c >> 8); pkt[ihl + 3] = (unsigned char)c;
pkt[10] = 0; pkt[11] = 0; /* recompute IP header checksum */
c = cksum(pkt, ihl);
pkt[10] = (unsigned char)(c >> 8); pkt[11] = (unsigned char)c;
slip_send((char *)pkt, len);
}
}
|