Multiple ethernet interfaces? Don’t settle for just one.

If you’re using a server that has multiple IP’s, you may want to use a random one with each call of a script, or outbound call. Here’s how you could do that.

<?php
// use the system to provide a neat and tidy comma separated string
// explode it by those commas
$ips = explode(',',`ip -4 addr | grep -oP "(10\.98\.76\.5.)" | sort -u | tr "\\n" "," | sed 's/,$//'`);
 
// get some closure
$ip = function(&$ips) {
        return $ips[array_rand($ips)];
};
 
// create options for the web socket-to-be
$options = array(
    'socket' => array(
        // calling the closure to get a random IP address
        'bindto' => $ip().':'.rand(1234,54321),
    ),
);
 
// create the context...
$context = stream_context_create($options);
 
// ...and use it to fetch the data
// , using the context, with the options
// , containing the IP to be bound.
echo file_get_contents('http://freegeoip.net/json/', false, $context).PHP_EOL;
 
exit;
?>

Hope you find that useful.

Author: Mike on May 14, 2015
Category: PHP, Tutorials

Comments are closed.

Last articles