Generate Hash of Interfaces and IP Addresses of Host
This is fairly messy, so any input on a better way to go about doing this is greatly appreciated.
I needed a way to parse the output of 'ifconfig' to generate a hash of the network interface to its IP address (in PHP). The following is what I've come up with.
We parse through the 'ifconfig' output and break out each interface based on '\n and not a \t', but neep to keep the character broken at, otherwise it will get discarded in the split. We then traverse through the exploded array and combine any of the single character values with the next line (as this is missing, but captured, character from the split). During this, we also filter out any interfaces that do not have 'inet x.x.x.x' address.
function getInterfaceHash() {
$ifconfig = shell_exec('ifconfig');
$ifconfig = preg_split('#\n([^\t])#', $ifconfig, -1, PREG_SPLIT_DELIM_CAPTURE);
$addresses = array();
$i = 0;
while (isset($ifconfig[$i])) {
$string = $ifconfig[$i];
if (strlen($ifconfig[$i]) === 1) {
$string = $ifconfig[$i] . $ifconfig[$i+1];
unset($ifconfig[$i+1]);
$i++;
}
if (preg_match('#\A(.+?):.+?inet\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s#s', $string, $matches)) {
$addresses[$matches[1]] = $matches[2];
}
$i++;
}
return $addresses;
}
Written by Alex
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Tags
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#