• 本站域名:OceanCoder.cn 若您喜欢本站,请添加至收藏夹!
  • 网站少部分资源来源自网络,如有侵犯您的权益,请联系站长删除!
  • 本站所有文章,除特殊标明外,皆为本人原创,转载请注明出处,谢谢合作!
  • 本站所下载的资源,若无特殊说明,使用统一解压密码:oceancoder.cn
  • 本站已实现布局自适应,支持手机端、pad端访问,欢迎体验
  • 本站部分资源可通过微信公众号留言获取,欢迎体验

Unity3D发布webGL后,向服务端推送用户的网络IP和本机IP

Unity3D OceanCoder 2019-07-30 4224 次浏览 0个评论

不清楚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";
}
}




已有 4224 位网友参与,快来吐槽:

发表评论