vm: fix potential null deref
[minix.git] / commands / ping / ping.c
blobde6c66c008b02fd83f601e1ec1de760a9cee1bd9
1 /*
2 ping.c
3 */
5 #define DEBUG 1
7 #include <sys/types.h>
8 #include <errno.h>
9 #include <signal.h>
10 #include <net/gen/netdb.h>
11 #include <sys/ioctl.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <unistd.h>
15 #include <net/gen/oneCsum.h>
16 #include <fcntl.h>
17 #include <net/gen/in.h>
18 #include <net/gen/inet.h>
19 #include <net/gen/ip_hdr.h>
20 #include <net/gen/icmp_hdr.h>
21 #include <net/gen/ip_io.h>
23 #define WRITE_SIZE 30
24 char buffer[16*1024];
26 int main(int argc, char *argv[]);
28 #if DEBUG
29 #define where() fprintf(stderr, "%s %d:", __FILE__, __LINE__);
30 #endif
32 #if __STDC__
33 #define PROTO(x,y) x y
34 #else
35 #define PROTO(x,y) X ()
36 #endif
38 PROTO (int main, (int argc, char *argv[]) );
39 static PROTO (void sig_hand, (int signal) );
41 main(argc, argv)
42 int argc;
43 char *argv[];
45 int fd, i;
46 int result, result1;
47 nwio_ipopt_t ipopt;
48 ip_hdr_t *ip_hdr;
49 int ihl;
50 icmp_hdr_t *icmp_hdr;
51 ipaddr_t dst_addr;
52 struct hostent *hostent;
53 int length;
55 if (argc<2 || argc>3)
57 fprintf(stderr, "Usage: %s hostname [length]\n", argv[0]);
58 exit(1);
60 hostent= gethostbyname(argv[1]);
61 if (!hostent)
63 dst_addr= inet_addr(argv[1]);
64 if (dst_addr == -1)
66 fprintf(stderr, "%s: unknown host (%s)\n",
67 argv[0], argv[1]);
68 exit(1);
71 else
72 dst_addr= *(ipaddr_t *)(hostent->h_addr);
73 if (argc == 3)
75 length= strtol (argv[2], (char **)0, 0);
76 if (length< sizeof(icmp_hdr_t) + IP_MIN_HDR_SIZE)
78 fprintf(stderr, "%s: length too small (%s)\n",
79 argv[0], argv[2]);
80 exit(1);
83 else
84 length= WRITE_SIZE;
86 fd= open ("/dev/ip", O_RDWR);
87 if (fd<0)
88 perror("open"), exit(1);
90 ipopt.nwio_flags= NWIO_COPY | NWIO_PROTOSPEC;
91 ipopt.nwio_proto= 1;
93 result= ioctl (fd, NWIOSIPOPT, &ipopt);
94 if (result<0)
95 perror("ioctl (NWIOSIPOPT)"), exit(1);
97 result= ioctl (fd, NWIOGIPOPT, &ipopt);
98 if (result<0)
99 perror("ioctl (NWIOGIPOPT)"), exit(1);
101 for (i= 0; i< 20; i++)
103 ip_hdr= (ip_hdr_t *)buffer;
104 ip_hdr->ih_dst= dst_addr;
106 icmp_hdr= (icmp_hdr_t *)(buffer+20);
107 icmp_hdr->ih_type= 8;
108 icmp_hdr->ih_code= 0;
109 icmp_hdr->ih_chksum= 0;
110 icmp_hdr->ih_chksum= ~oneC_sum(0, (u16_t *)icmp_hdr,
111 WRITE_SIZE-20);
112 result= write(fd, buffer, length);
113 if (result<0)
115 perror("write");
116 exit(1);
118 if (result != length)
120 where();
121 fprintf(stderr, "result= %d\n", result);
122 exit(1);
125 alarm(0);
126 signal (SIGALRM, sig_hand);
127 alarm(1);
129 result= read(fd, buffer, sizeof(buffer));
130 if (result>= 0 || errno != EINTR)
131 break;
133 if (i >= 20)
135 printf("no answer from %s\n", argv[1]);
136 exit(1);
138 if (result<0)
140 perror ("read");
141 exit(1);
143 printf("%s is alive\n", argv[1]);
144 exit(0);
147 static void sig_hand(signal)
148 int signal;