4

I am connected to a lan.. I can access internet. using the browser I can find my public ip using the search "what is my ip".

I want to get the public ip using php

I am running the script in my localhost wamp server..

I tried:

$_SERVER['REMOTE_ADDR'] and $_SERVER['SERVER_ADDR']` both give me `localhost ip ::1

Is there any networking functions that can give me my public ip address?

is there any way without using any external service? because if I use an external service, it may not available in the future.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Sugumar Venkatesan
  • 4,019
  • 8
  • 46
  • 77

5 Answers5

8

try this please:

$externalContent = file_get_contents('http://checkip.dyndns.com/');
preg_match('/Current IP Address: \[?([:.0-9a-fA-F]+)\]?/', $externalContent, $m);
$externalIp = $m[1];

Or use httpbin.org/ip as Priyesh Kumar suggests

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
6

You can use API to get public IP address from localhost.

https://www.ipify.org/

<?php
    $ip = file_get_contents('https://api.ipify.org');
    echo "My public IP address is: " . $ip;
?>
dhaval
  • 190
  • 7
-1

try this too and check with print_r

$ip= isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
Joseph
  • 11
  • 8
-1

I Think you should use $_SERVER['REMOTE_ADDR'] to get the IP address of the router

-1

Try this as it is tested on local machine(localhost)

$ip = file_get_contents('https://api.ipify.org'); echo $ip;