Created
November 1, 2016 15:53
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 16 should be
$gw_rev = long2ip(hexdec("0x$gw_hex"));
to work with modern PHP.