不清楚Unity3D WebGL怎么获取用户的网络IP和本机IP,所以本文采用的方案是使用JS获取并传递给Unity,再向服务端推送。
具体实现如下:
一、Unity3D WebGL发布之前的准备
Unity程序调用Javascript方法,此处通知js获取IP并传递给后台。
Unity2017以后的版本中,与js通讯的方法与旧版本不同,具体如下:
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
1、新建文件IPHelper.jslib文件,然后放到Assets\Plugins目录下,内容如下:
mergeInto(LibraryManager.library, {
GetIpInfo: function () {
var returnStr = GetWebIP()+"-"+GetLocalIP();
var bufferSize = lengthBytesUTF8(returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
},
});2、Unity中这么写:
[DllImport("__Internal")]
private static extern string GetIpInfo();
private string _IpStr = "";
void Start () {
_IpStr = GetIpInfo();
}这样写在Start中,在Web版本启动后,会通知js获取IP地址并返回,然后向服务端传递即可。
二、Unity3D WebGL发布之后的准备
1、修改index.html文件,<head>中添加如下内容
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> <script src="IPHelper.js"></script>
2、IPHelper.js文件内容如下:
function getUserIP(onNewIP) {
//compatibility for firefox and chrome
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new myPeerConnection({
iceServers: []
}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
function iterateIP(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
pc.createDataChannel("");
pc.createOffer().then(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
}).catch(function(reason) {
});
pc.onicecandidate = function(ice) {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
var CLocalIpStr='';
getUserIP(function(ip){
CLocalIpStr = ip;
});
function GetLocalIP(){
return CLocalIpStr;
}
function GetWebIP(){
if("undefined" != typeof returnCitySN){
return returnCitySN["cip"];
}else{
return "0.0.0.0";
}
}
已有 6223 位网友参与,快来吐槽:
发表评论