xref: /plan9-contrib/sys/src/cmd/ip/dhcpd/ping.c (revision 3f9c83932f326ae8b6d81b36429957bc06a9813e)
1 #include <u.h>
2 #include <libc.h>
3 #include <ip.h>
4 #include "../icmp.h"
5 
6 static void
7 catch(void *a, char *msg)
8 {
9 	USED(a);
10 	if(strstr(msg, "alarm"))
11 		noted(NCONT);
12 	else
13 		noted(NDFLT);
14 }
15 
16 #define MSG "dhcp probe"
17 
18 /*
19  *  make sure noone is using the address
20  */
21 int
22 icmpecho(uchar *a)
23 {
24 	int fd;
25 	char buf[512];
26 	Icmp *ip;
27 	int i, n, len;
28 	ushort sseq, x;
29 	int rv;
30 
31 	rv = 0;
32 
33 	sprint(buf, "%I", a);
34 	fd = dial(netmkaddr(buf, "icmp", "1"), 0, 0, 0);
35 	if(fd < 0){
36 		return 0;
37 	}
38 
39 	sseq = getpid()*time(0);
40 
41 	ip = (Icmp*)buf;
42 	notify(catch);
43 	for(i = 0; i < 3; i++){
44 		ip->type = EchoRequest;
45 		ip->code = 0;
46 		strcpy((char*)ip->data, MSG);
47 		ip->seq[0] = sseq;
48 		ip->seq[1] = sseq>>8;
49 		len = ICMP_IPSIZE+ICMP_HDRSIZE+sizeof(MSG);
50 
51 		/* send a request */
52 		if(write(fd, buf, len) < len)
53 			break;
54 
55 		/* wait 1/10th second for a reply and try again */
56 		alarm(100);
57 		n = read(fd, buf, sizeof(buf));
58 		alarm(0);
59 		if(n <= 0)
60 			continue;
61 
62 		/* an answer to our echo request? */
63 		x = (ip->seq[1]<<8)|ip->seq[0];
64 		if(n >= len)
65 		if(ip->type == EchoReply)
66 		if(x == sseq)
67 		if(strcmp((char*)ip->data, MSG) == 0){
68 			rv = 1;
69 			break;
70 		}
71 	}
72 	close(fd);
73 	return rv;
74 }
75