Skip to content

Instantly share code, notes, and snippets.

@kamermans
Created November 1, 2016 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamermans/f7ccdca41584e9318a474f1313f8b43c to your computer and use it in GitHub Desktop.
Save kamermans/f7ccdca41584e9318a474f1313f8b43c to your computer and use it in GitHub Desktop.
Example of retrieving the Docker host IP from within a container via PHP by parsing the Linux kernel's routing table
<?php
$gw = "Unknown";
// Get the Docker host IP from the routing table
$table = file("/proc/net/route");
foreach ($table as $row) {
// Split the fields out of the routing table
$fields = preg_split("/[\t ]+/", trim($row));
// Skip this route if it's not the default gateway
if ($fields[1] != "00000000") continue;
// Convert the hex gateway IP to dotted-notation
$gw_hex = $fields[2];
$gw_rev = long2ip("0x$gw_hex");
$gw = implode(".", array_reverse(explode(".", $gw_rev)));
break;
}
echo "Docker host IP: $gw\n";
@tushev
Copy link

tushev commented Apr 8, 2023

Line 16 should be $gw_rev = long2ip(hexdec("0x$gw_hex")); to work with modern PHP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment