#!/usr/local/bin/php
<?php
/* di-ip.php by David Sklar <tech-php at sklar.com>
*
* This program retrieves the WAN IP address that a DLink DI-704(P)
* router is assigned. It logs in to the router if necessary.
*
* Once the program logs into the router, then any access from the IP
* address that the program logs in from is permitted, so take care
* not to run this program on a system where other users could make
* malicious requests to your router.
*
* This program requires PHP 4 with the cURL extension.
*/
/*
* CONFIGURATION
*/
/* Set $router_ip to the hostname or IP address of your DI704.
* e.g. 192.168.0.1 */
$router_ip = '192.168.0.1';
/* Set $router_password to the administrative password of your DI704.
* Anyone who can read this script can read the password, so be careful
* with your permissions. */
$router_password = 'password';
/*********************************************************************/
if (! function_exists('curl_init')) {
die("This program requires the cURL extension.");
}
/* Get the login form */
$c = curl_init("http://$router_ip/menu.htm?RC=@");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$login_page = curl_exec($c);
curl_close($c);
/* If we're not already logged in, log in */
if (! preg_match("/Administrator's Main Menu/",$login_page)) {
// parse variables out of login page
preg_match_all('/<INPUT TYPE=HIDDEN VALUE="([^"]+?)" NAME=([^>]+?)>/',
$login_page, $matches, PREG_SET_ORDER);
$post_fields = array();
foreach ($matches as $match) {
$post_fields[] = urlencode($match[2]) . '=' . urlencode($match[1]);
/* The password (in the URL field) has to go right after the PSWD
* field for login to succeed */
if ($match[2] == 'PSWD') {
$post_fields[] = 'URL='.urlencode($router_password);
}
}
$c = curl_init("http://$router_ip/cgi-bin/logi");
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, implode('&',$post_fields));
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$admin_page = curl_exec($c);
curl_close($c);
if (! preg_match("/Administrator's Main Menu/",$admin_page)) {
die("Can't login");
}
}
/* Get the Status page */
$c = curl_init("http://$router_ip/status.htm");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$status_page = curl_exec($c);
curl_close($c);
/* Look for the IP address */
if (preg_match('{<TD BGCOLOR=#006693 WIDTH=35%><font color=#ffffff>IP Address</font></TD><TD ALIGN=CENTER WIDTH=40%>([0-9/.]+)</TD>}',$status_page,$matches)) {
print $matches[1];
} else {
die("Can't get IP Address");
}
?>