Obtaining a Visitor's IP Address

Question: How we can track the user IP address of the person who using Internet explorer and add the ip value into text input field?

Answer: This can't be done with Javascript as Javascript does not have access to the internet and knows nothing about IP addresses (Javascript is downloaded to your visitor's computer and runs there).

The only way to obtain the IP address indirectly from within JavaScript is to have JavaScript call Java (if it is installed in the browser) and have the Java retrieve the IP address and return it to JavaScript.

if (java && java.net)
ip = ''+java.net.InetAddress.getLocalHost().getHostAddress();
else ip = 'unknown';

The better way to obtain the IP address of your visitor without having to rely on anything actually having been installed into the browser is to use a server side script eg. ASP, PHP, JSP, or PERL. These can obtain the IP address from an environment variable called REMOTE_ADDR. PRovided that your JavaScript has the appropriate suffix on the file name to run the appropriate server side scripting language first you can use one of the following statements in your JavaScript to load the IP address into a JavaScript variable called 'ip'.


ip = '<--#echo var="REMOTE_ADDR"-->';


ip = "<?php echo $_SERVER['REMOTE_ADDR']?>";


ip = '<%= Request.ServerVariables("REMOTE_ADDR")%>';


ip = '<%= Request.UserHostAddress>';


ip = '<%=request.getRemoteAddr()%>';


ip = '<cfoutput>#cgi.remote_addr#</cfoutput>';


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow