How to obtain a user's IP address

For some of our API queries the user's IP address is necessary. Below we have provided examples of how to obtain this IP address in a few languages.



Python

The following will return the client's IP address when run as a CGI script:

import cgi
import os

ip_addr = os.environ["REMOTE_ADDR"]


Perl

The following will return the client's IP address when run as a CGI script:

$ip = $ENV{'REMOTE_ADDR'};


PHP

In almost all cases the following PHP code will return the client's IP address:

$ip=$_SERVER['REMOTE_ADDR'];
However, it is possible that the above code will return the IP address of a proxy-server, and not the actual client. The code below has a better chance of retrieving the actual client's IP address:
if (isset($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}



Ruby

Use the following the get the client's IP address:

ip_addr = request.env['REMOTE_ADDR']

However, some say that the following is a better approach as it handles proxy-servers better:

ip_addr = request.remote_ip


ASP.NET

Use the following the get the client's IP address:

ip_addr = Request.ServerVariables("REMOTE_ADDR")


Java

Use the following the get the client's IP address:

String ip_addr = request.getRemoteAddr();

However, some say that the following is a better approach as it handles proxy-servers better:

String ip_addr = request.getHeader("X-FORWARDED-FOR");
if(id_addr == null)
{
ip_addr = request.remote_ip
}


iPhone C Code

Unfortuately the iPhone SDK provides no simple way to get the device's current IP address. However, there do seem to be some workable solutions out there. The following resources may help:

http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone
http://iphonesdksnippets.com/post/2009/09/07/Get-IP-address-of-iPhone.aspx

Free 14-Day Trial

Sign Up Now!

Get started right away!