Can I get my IP address in a chrome app without using an external service?

前端 未结 3 351
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 06:29

I am building a chrome app and created a UDP socket via the chrome socket api.

Is there a way to retrieve your own IP address without u

3条回答
  •  隐瞒了意图╮
    2021-01-22 06:58

    The callback you provide to udp.create() is called when the socket has been initially created, not when the socket receives packets. At creation time, the socket is not associated with any localAddress or localPort yet. You have to call udp.bind() to establish the specific localPort (and optionally a specific localAddress) that the socket will listen for packets on. If you bind() to "0.0.0.0" then the socket will listen on all local IPs.

    When a new packet arrives, the udp.onReceive event is triggered. The packet was received by a specific localAddress, however the Chrome API does not provide a means of directly querying which localAddress received the packet (the underlying recvfrom() socket function does not provide that information). To discover the receiving local IP, you would have to either:

    1. bind the socket to a specific localAddress, as that will be the only local IP that can trigger the onReceive event for that socket.

    2. check the list of interfaces reported by chrome.system.network.getNetworkInterfaces(). If 1 interface is reported, that will be the interface receiving all packets, so you can use its address. However, if 2+ interfaces are reported, you will have to parse the network prefix from the packet's remoteAddress and compare that value to the prefix of each reported interface until you find a match (assuming the sender is broadcasting from the same network subnet that the local machine is connected to, and not broadcasting across subnet boundaries).

    That being said, all of this is only relevant if you need to put your local IP in the broadcast reply's data payload. Say there are 3 local interfaces, and the broadcast packet is received on interface 2. Replying with the localAddress of interface 1 or 3 would obviously be wrong, as they are on different networks than the broadcaster. However, if you DO NOT need to put your localAddress in the reply's payload, then the broadcaster can simply look at the remoteAddress of the reply to know what your IP address is. Then you do not need to figure out your local IP at all, the OS will handle everything for you when you send the reply to the remoteAddress/remotePort that you received the broadcast from.

提交回复
热议问题