Advertisement
yakar

[python] Ping

Dec 31st, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import threading
  2. import time
  3. import socket
  4. import os
  5. import struct
  6. from netaddr import IPNetwork, IPAddress
  7. #from ICMPHeader import ICMP
  8. import ICM
  9. import ctypes
  10.  
  11. # host to listen on
  12. HOST = '192.168.1.1'
  13. # subnet to target (iterates through all IP address in this subnet)
  14. SUBNET = '192.168.1.0/24'
  15. # string signature
  16. MESSAGE = 'hellooooo'
  17.  
  18. # sprays out the udp datagram
  19. def udp_sender(SUBNET, MESSAGE):
  20. time.sleep(5)
  21. sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  22. for ip in IPNetwork(SUBNET):
  23. try:
  24. sender.sendto(MESSAGE, ("%s" % ip, 65212))
  25. except:
  26. pass
  27.  
  28. def main():
  29. t = threading.Thread(target=udp_sender, args=(SUBNET, MESSAGE))
  30. t.start()
  31.  
  32. socket_protocol = socket.IPPROTO_ICMP
  33. sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
  34. sniffer.bind(( HOST, 0 ))
  35. sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  36.  
  37. # continually read in packets and parse their information
  38. while 1:
  39. raw_buffer = sniffer.recvfrom(65565)[0]
  40. ip_header = raw_buffer[0:20]
  41. iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)
  42.  
  43. # Create our IP structure
  44. version_ihl = iph[0]
  45. ihl = version_ihl & 0xF
  46. iph_length = ihl * 4
  47. src_addr = socket.inet_ntoa(iph[8]);
  48.  
  49. print("ICMP:%s" % ctypes.sizeof(ICMP))
  50.  
  51. # Create our ICMP structure
  52. buf = raw_buffer[iph_length:iph_length + ctypes.sizeof(ICMP)]
  53. icmp_header = ICMP(buf)
  54.  
  55. # check for the type 3 and code and within our target subnet
  56. if icmp_header.code == 3 and icmp_header.type == 3:
  57. if IPAddress(src_addr) in IPNetwork(SUBNET):
  58. if raw_buffer[len(raw_buffer) - len(MESSAGE):] == MESSAGE:
  59. print("Host up: %s" % src_addr)
  60.  
  61. if __name__ == '__main__':
  62. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement