ping.c 1.1 KB

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