
通过访问第三方IP查询服务,可以快速获取到本地公网IP地址。常用的服务有:
现代浏览器提供相关的API,可以直接获取本地公网IP地址。以JavaScript为例,可以使用RTCPeerConnectionAPI来获取:
function getPublicIP(onNewIP) {
// compatibility for firefox and chrome
var pc = new RTCPeerConnection({
// Don't gather stun/turn candidates
iceServers: []
}),
noop = function() {};
pc.createDataChannel(""); // create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop); // create offer and set local description
pc.onicecandidate = function(ice) { // listen for candidate events
if (ice && ice.candidate && ice.candidate.candidate) {
var publicIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
onNewIP(publicIP);
pc.onicecandidate = noop;
}
};
}
这种方法兼容性较好,可以直接在浏览器中使用,但需要自行实现。
在命令行中,可以使用系统自带的工具来获取本地公网IP地址。以Windows为例,可以使用ipconfig命令:
C:\>ipconfig /all
...
IPv4 Address. . . . . . . . . . . : 1.2.3.4
...
以Linux/macOS为例,可以使用curl命令:
$ curl ifconfig.me
1.2.3.4
这种方法直接使用系统命令,不需要额外引入第三方库,但需要针对不同操作系统编写不同的代码。