advertisement -- please support sponsors

getting the user's IP address

How can I obtain the Host Name and IP Address of the user who is accessing my page?

-- David

Although JavaScript does not provide direct support for obtaining the user's host name and address, it does give you access to the standard Java classes. And within those classes is one called "," which has everything you need to get the user's host name and address.

My guess is that you wouldn't be trying to do this unless you were among the more experienced JavaScript users, so I won't bore you with a lot of talk. Here is the code, and here is what it does:

The following source...


/* There are a few instances in which the browser cannot ascertain the user's address, so we will instruct the browser to ignore errors by setting the onerror handler to null: */
window . onerror = null;

/* We will also give hostaddress and hostname a default value in case the address look-up fails: */
hostaddress = hostname = "(unknown)";

/* Now we will try to gather the host information: */
localhost = java . net . InetAddress . getLocalHost ();
hostaddress = localhost . getHostAddress ();
hostname = localhost . getHostName ();

/* The Java methods used above are capable of throwing exceptions. When Java exceptions occur within JavaScript, the script body is aborted. In order to make sure that the following statements get a chance to execute, we must include them in a separate script body: */



document . writeln ("<p>Your IP address is <b>" + hostaddress + "</b>.</p>");
document . writeln ("<p>Your hostname is <b>" + hostname + "</b>.</p>");

</script> <p>
Any questions?</p>

...produces the following results:*

Any questions?

* This script might not work for you if you are using a dial-up connection to the Internet (due to the fact that your IP address changes each time you reconnect).

For more information on the class, visit JavaSoft's web site.

For another good example of how Java classes can be used within JavaScript, please see "Determining the User's Screen Size."

Charlton Rose
April 29, 1997