如何使用javascript获取运行应用程序的主机IP和端口号 [英] how to get host IP and port number on which the application is running using javascript
问题描述
任何人都可以告诉我如何使用javascript获取运行Web应用程序的主机IP和端口号(例如127.0.0.1:8080)
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直接获取IP地址。它没有在 window.location
对象中公开。
I'm afraid it's not possible to directly obtain the IP address via Javascript. It's not exposed in the window.location
object.
部分原因是随后访问地址:port
在语义上与访问 hostname:port
不同 - 它们在技术上是不同的URL。
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.
如果你真正追求的是当前webapp下载的URL的主机部分,你需要:
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
并检查它是否是 http:
(即端口80)或 https:
(端口443)。
and check whether it's http:
(i.e. port 80) or https:
(port 443).
您还可以使用:
window.location.host
将包含主机名
和端口
作为冒号 - 分隔字符串,与上述相同的警告,如果通过协议的默认端口访问内容,则将省略:port
部分。
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.
这篇关于如何使用javascript获取运行应用程序的主机IP和端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!