Question

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']; ?>
Was it helpful?

Solution 3

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

The PHP $_SERVER variables can be checked at this link.

I am sure that 'REMOTE_ADDR' returns 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.

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

//  in place of $_SERVER['SERVER_NAME']
$_SERVER['HTTP_X_FORWARDED_HOST'] && $_SERVER['HTTP_X_FORWARDED_SERVER']

OTHER TIPS

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

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

Getting the origin IP and Port of a client

The correct answer for those with minimal networking knowledge

Completing the @marcolz answer with an explicative text.

TL;DR - echo $_SERVER['REMOTE_ADDR'] . ":" . $_SERVER['REMOTE_PORT'];

The meaning behind it:

As everyone should know, it's important to have data about each requisition your clients did, logging their access data for at least five years to come for self protection in case of a legal dispute over copyrights or anything else your users might get themselves into.

The IPv4 world is made of ASN (Autonomous System Number) owners and those who they share their identity with, the so called final user.

As IPv4 has become scarce, most ISPs (Internet Service Providors) provide access to the World Wide Web through very big and huge NAT (Network Address Transtation) called CG-NAT (Carrier Grade Network Address Translation) for those clients who didn't pay enough to be worth a public IPv4 block for themselves, basically all the final user's connections are made through this and the only way to know who was the smartass when something happen is by knowing not only their IP address, but also the port they used on the request.

If you are using PHP on your application you can protect yourself by logging the request origin IP and port.

To do so you can use the following code:

echo $_SERVER['REMOTE_ADDR'] . ":" . $_SERVER['REMOTE_PORT'];

Here we concatenate the request origin IP address and port with a colon in the middle, echoing them in order to see the result.

You can check the veracity of the information by doing the request while listening on tcpdump, if the port used in the request on tcpdump is the same as the one your browser shows then everything worked as expected.

Cheers from the outerworld!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top