icmpv6_socket.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. module ICMPV6
  2. class ICMPV6Socket
  3. require 'socket'
  4. require_relative 'icmpv6_packet.rb'
  5. def initialize
  6. @icmp_socket = Socket.new(Socket::PF_INET6, Socket::SOCK_RAW, Socket::IPPROTO_ICMPV6)
  7. end
  8. def send(destination, packet)
  9. @icmp_socket.send(packet, 0, destination)
  10. response = @icmp_socket.recvfrom(9000)
  11. return response
  12. end
  13. # Poor implementation of the ping command.
  14. def ping(host, count = 1)
  15. def create_destination(host)
  16. return Addrinfo.new(Socket.pack_sockaddr_in(0, host))
  17. end
  18. destination = create_destination(host)
  19. packet = Packet.new(message_type: 128)
  20. packet.payload.identifier = EchoRequest.random_identifier
  21. packet.payload.payload = EchoRequest.sample_payload
  22. successful = 0
  23. count.times do
  24. response = send(destination, packet.to_binary_s)
  25. response_packet = Packet.read(response[0])
  26. if response[1].ip_address == destination.ip_address &&
  27. response_packet.payload.payload = packet.payload.payload &&
  28. response_packet.payload.identifier == packet.payload.identifier &&
  29. response_packet.payload.sequence == packet.payload.sequence
  30. successful += 1
  31. end
  32. packet.payload.sequence += 1
  33. packet.payload.sequence = 0 unless packet.payload.sequence < 2**16
  34. end
  35. return successful
  36. end
  37. def close
  38. @icmp_socket.close unless @icmp_socket.closed?
  39. end
  40. end
  41. end