How can I get the IP address and port of a client

2019-09-02 20:31发布

How do I get the IP and port of a client with PHP?

I tried the script below but it only gives me the IP address.

<?php print $_SERVER['REMOTE_ADDR']; ?>

标签: php ip client port
3条回答
Melony?
2楼-- · 2019-09-02 21:18

To get the port of the connected device you can use $_SERVER['REMOTE_PORT']

$ipAddress=$_SERVER['REMOTE_ADDR']; $port=$_SERVER['REMOTE_PORT'];

查看更多
小情绪 Triste *
3楼-- · 2019-09-02 21:19

Port is defined in http server (Apache or other and mostly it is 80 or 443)

The php $_SERVER variables you can check at : http://www.php.net/manual/en/reserved.variables.server.php

I am sure that : REMOTE_ADDR' The IP address from which the user is viewing the current page.

But if your server is behind NAT:

If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.

$_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR']

$_SERVER['HTTP_X_FORWARDED_HOST'] and $_SERVER['HTTP_X_FORWARDED_SERVER'] in place of $_SERVER['SERVER_NAME']

:-)

查看更多
疯言疯语
4楼-- · 2019-09-02 21:35

Try this:

if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = $_SERVER['REMOTE_ADDR'];
}
else {
    $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
查看更多
登录 后发表回答