PHP获取真实的网络IP

function get_client_ip() {

    $ip = $_SERVER['REMOTE_ADDR'];

    if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {

        $ip = $_SERVER['HTTP_CLIENT_IP'];

    } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {

        foreach ($matches[0] AS $xip) {

            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {

                $ip = $xip;

                break;

            }

        }

    }

	//  A类:10.0.0.0-10.255.255.255

	//	B类:172.16.0.0-172.31.255.255 

	//	C类:192.168.0.0-192.168.255.255

	//局域网IP或者本地IP段开头

	$juyuwangIps = array( '10.' , '127.0.0.1' , '192.168.' );

	for( $i = 16 ; $i <= 31 ; $i++ )

	{

		$juyuwangIps[] = '172.' . $i . '.';

	}

	//如果是本地IP则找出网络IP

	foreach( $juyuwangIps as $cIp )

	{

		if( strpos( $ip ,$cIp ) === 0 )

		{

			if( $wIp = get_onlineip() )

			{

				$ip = $wIp;

			}

			break;

		}

	}

	

    return $ip;

}

function get_onlineip() {

    $ch = curl_init('http://1111.ip138.com/ic.asp');

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $a  = curl_exec($ch);

    preg_match('/\[(.*)\]/', $a, $ip);

	if( is_array( $ip ) && isset( $ip[1] ) && !empty( $ip[1] )  )

	{

		return $ip[1];

	}

    return '';

 }

  

你可能感兴趣的:(PHP)