Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get host IP and port number on which the application is running using javascript

can anyone tell me how to get host IP and port number on which the web application is running using javascript (e.g. 127.0.0.1:8080)

like image 200
pankaj Avatar asked Sep 26 '12 11:09

pankaj


2 Answers

I'm afraid it's not possible to directly obtain the IP address via Javascript. It's not exposed in the window.location object.

Part of the reason for that is that subsequently accessing address:port is not semantically the same as accessing hostname:port - they are technically different URLs.

If what you're actually after is the host portion of the URL from which the current webapp was downloaded, you need:

window.location.hostname
window.location.port

The latter could be blank if the "default" port is being used, so you would also need to read:

window.location.protocol

and check whether it's http: (i.e. port 80) or https: (port 443).

You can also use:

window.location.host

which will contain both the hostname and the port as colon-separated strings, with the same caveat as above that the :port section will be omitted if the content was accessed via the "default" port for the protocol.

like image 107
Alnitak Avatar answered Oct 05 '22 19:10

Alnitak


document.location.host      // localhost:1234
document.location.hostname  // localhost
document.location.port      // 1234
like image 35
Eric Lennartsson Avatar answered Oct 05 '22 18:10

Eric Lennartsson