Javascript 如何使用javascript获取运行应用程序的主机IP和端口号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12600244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get host IP and port number on which the application is running using javascript
提问by pankaj
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)
谁能告诉我如何使用javascript(例如127.0.0.1:8080)获取运行Web应用程序的主机IP和端口号
回答by Alnitak
I'm afraid it's not possible to directly obtain the IP address via Javascript. It's not exposed in the window.location
object.
恐怕无法通过Javascript直接获取IP地址。它没有暴露在window.location
对象中。
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.
部分原因是后续访问address:port
在语义上与访问hostname:port
不同 - 它们在技术上是不同的 URL。
If what you're actually after is the host portion of the URL from which the current webapp was downloaded, you need:
如果您真正想要的是下载当前 web 应用程序的 URL 的主机部分,您需要:
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).
并检查它是http:
(即端口 80)还是https:
(端口 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.
它将包含hostname
和port
以冒号分隔的字符串,与上面相同的警告是,:port
如果内容是通过协议的“默认”端口访问的,则该部分将被省略。
回答by Eric Lennartsson
document.location.host // localhost:1234
document.location.hostname // localhost
document.location.port // 1234