You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.1 KiB

5 years ago
  1. <?php
  2. $data = "var tracepoints = {'points': [";
  3. define ("SOL_IP", 0);
  4. define ("IP_TTL", 2); // On OSX, use '4' instead of '2'.
  5. $dest_url = "google.com";
  6. $maximum_hops = 30;
  7. $port = 33434;
  8. function ip2geo ($host) {
  9. global $argv;
  10. // Get GeoIP info
  11. @$data = file_get_contents('http://ipinfo.io/'.$host);
  12. if ($data) {
  13. $data = json_decode($data);
  14. return $data->loc;
  15. } else {
  16. // An error has accourred
  17. return "(No geo info found)";
  18. }
  19. }
  20. $dest_addr = gethostbyname ($dest_url);
  21. $ttl = 1;
  22. while ($ttl < $maximum_hops) {
  23. // Create ICMP and UDP sockets
  24. $recv_socket = socket_create (AF_INET, SOCK_RAW, getprotobyname ('icmp'));
  25. $send_socket = socket_create (AF_INET, SOCK_DGRAM, getprotobyname ('udp'));
  26. // Set TTL to current lifetime
  27. socket_set_option ($send_socket, SOL_IP, IP_TTL, $ttl);
  28. // Bind receiving ICMP socket to default IP (no port needed since it's ICMP)
  29. socket_bind ($recv_socket, 0, 0);
  30. // Save the current time for roundtrip calculation
  31. $t1 = microtime (true);
  32. // Send a zero sized UDP packet towards the destination
  33. socket_sendto ($send_socket, "", 0, 0, $dest_addr, $port);
  34. // Wait for an event to occur on the socket or timeout after 5 seconds. This will take care of the
  35. // hanging when no data is received (packet is dropped silently for example)
  36. $r = array ($recv_socket);
  37. $w = $e = array ();
  38. socket_select ($r, $w, $e, 5, 0);
  39. // Nothing to read, which means a timeout has occurred.
  40. if (count ($r)) {
  41. // Receive data from socket (and fetch destination address from where this data was found)
  42. socket_recvfrom ($recv_socket, $buf, 512, 0, $recv_addr, $recv_port);
  43. $recv_geo = ip2geo ($recv_addr);
  44. $recv_geo_split = explode(",", $recv_geo);
  45. $data .= sprintf("{'x':%s,'y':%s},", $recv_geo_split[0], $recv_geo_split[1]);
  46. }
  47. socket_close ($recv_socket);
  48. socket_close ($send_socket);
  49. $ttl++;
  50. if ($recv_addr == $dest_addr) break;
  51. }
  52. $data = substr($data, 0, -1) . "]}";
  53. printf ("%s\n", $data);
  54. $fp = fopen('traceroute.js', 'w');
  55. fwrite($fp, json_encode($data));
  56. fclose($fp);
  57. ?>