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

后端 未结 2 1338
暖寄归人
暖寄归人 2021-01-12 14:40

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)

2条回答
  •  -上瘾入骨i
    2021-01-12 14:51

    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.

提交回复
热议问题