Unity学习Unity获取Android手机局域网(WIFI)IP

Posted 致力于游戏开发的菜鸡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity学习Unity获取Android手机局域网(WIFI)IP相关的知识,希望对你有一定的参考价值。

编写.java文件,导入Unity。
unity版本必须大于2018.2及以上。

//JAVA
package com.test1;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 

 
public class test {
    //匹配C类地址的IP
    public static final String regexCIp = "^192\\\\.168\\\\.(\\\\d{1}|[1-9]\\\\d|1\\\\d{2}|2[0-4]\\\\d|25\\\\d)\\\\.(\\\\d{1}|[1-9]\\\\d|1\\\\d{2}|2[0-4]\\\\d|25\\\\d)$";
    //匹配A类地址
    public static final String regexAIp = "^10\\\\.(\\\\d{1}|[1-9]\\\\d|1\\\\d{2}|2[0-4]\\\\d|25\\\\d)\\\\.(\\\\d{1}|[1-9]\\\\d|1\\\\d{2}|2[0-4]\\\\d|25\\\\d)\\\\.(\\\\d{1}|[1-9]\\\\d|1\\\\d{2}|2[0-4]\\\\d|25\\\\d)$";
    //匹配B类地址
    public static final String regexBIp = "^172\\\\.(1[6-9]|2\\\\d|3[0-1])\\\\.(\\\\d{1}|[1-9]\\\\d|1\\\\d{2}|2[0-4]\\\\d|25\\\\d)\\\\.(\\\\d{1}|[1-9]\\\\d|1\\\\d{2}|2[0-4]\\\\d|25\\\\d)$";
 
 
    public  String getHostIp() {
        String hostIp;
        Pattern ip = Pattern.compile("(" + regexAIp + ")|" + "(" + regexBIp + ")|" + "(" + regexCIp + ")");
        Enumeration<NetworkInterface> networkInterfaces = null;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress address;
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                address = inetAddresses.nextElement();
                String hostAddress = address.getHostAddress();
                Matcher matcher = ip.matcher(hostAddress);
                if (matcher.matches()) {
                    hostIp = hostAddress;
                    return hostIp;
                }
 
            }
        }
        return null;
    }
}

编写Unity脚本:

using UnityEngine;
using UnityEngine.UI;


public class GetIPAddress : MonoBehaviour
{
    public Text text;
    // Start is called before the first frame update
    void Start()
    {
        androidJavaObject jo = new AndroidJavaObject("com.test1.test");
        AndroidJavaClass act = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        text.text = "IP:" + jo.Call<string>("getHostIp") + "  端口号:50000";
    }
}

打包发布Android端进行测试:
在这里插入图片描述

参考:Unity获取Android手机局域网(WIFI)内网ip,超级简单述

以上是关于Unity学习Unity获取Android手机局域网(WIFI)IP的主要内容,如果未能解决你的问题,请参考以下文章

Unity学习Unity获取Android手机局域网(WIFI)IP

unity3d怎么获取安卓手机相册路径

unity中获取手机电量

100个 Unity踩坑小知识点| Unity调用API ,动态获取Android权限,附带所有Android权限表格

2019版unity游戏开发学习路线

如何在 Unity 中检测 android 手机旋转?