#! /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 cocould 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 ");
}
?>