Some time you may want to show or capture client IP address for security reasons. Here are sample codes specific to language/script.
PHP :
echo $_SERVER[‘REMOTE_ADDR'];
Java :
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class IPAddress{
public static void main(String[] a) {
try {
InetAddress thisIp = InetAddress.getLocalHost();
System.out.print(thisIp.getHostAddress());
} catch (UnknownHostException ex) {
Logger.getLogger(study.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
C# :
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
VB.Net :
Public Shared Function GetIPAddress() As String
Dim context As System.Web.HttpContext = System.Web.HttpContext.Current
Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If String.IsNullOrEmpty(sIPAddress) Then
Return context.Request.ServerVariables("REMOTE_ADDR")
Else
Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c})
Return ipArray(0)
End If
End Function
Javascript :
$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
obj = JSON.parse(JSON.stringify(data, null, 2));
$('#ip').html(obj.ip);
});
No comments:
Post a Comment