Using PHP/cURL to grok your public IP address

I had the occasion to create a PHP page that displays the server’s current public IP address. Not necessarily a good thing to display. But, I have several internal web sites on a development server where the host names are not available on a public DNS server. Displaying the server’s current public IP address is handy to prevent needing to nslookup my dyndns host name when altering my host file.
So, here is how I did it:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$pattern = '/Your IP:  ([d]{1,3}.[d]{1,3}.[d]{1,3}.[d]{1,3})</span>/';
$matches = array();
preg_match($pattern, $output, $matches);
$yourIP = 'N/A';
if (count($matches) > 1) {
  $yourIP = $matches[1];

What I’m doing here is using cURL to get the page at and then using a regular expressing to get the IP address returned in that page.
Albeit not completely fault-tolerant, as the web site can change it’s structure, but this type of quick’n’dirty screen scraping was what I needed at the time.

One thought on “Using PHP/cURL to grok your public IP address”

  1. Hi Steven
    After googling I found your above post on obtaining your public IP address.
    I am trying to do much the same thing (except I’m after the Latitude and Longitude).
    But I tried your code and it doesn’t seem to work for me. You did say “the website could change its structure”. Can you point me in the right direction to get the IP or even better the Latitude and Longitude.
    Any help will be much appreciated.

Comments are closed.