Unity获取本机IP地址

Unity获取本机IP地址

目录


一.目的

1.想知道:Unity获取本机IP地址

二.参考

三.操作:一:完成:能够获取到IP地址

1.版本

  1. unity2018.4.0f1
  2. vs2017
  3. windows10 64位

1.运行结果

www.zeeklog.com  - Unity获取本机IP地址
www.zeeklog.com  - Unity获取本机IP地址

1.代码:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System;
using System.Net.NetworkInformation;


    /// <summary>
    /// 获取本机IP
    /// </summary>
    /// <returns>string :ip地址</returns>
    public string GetIP()
    {
        string output = "";

        foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
        {
            NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;  //无线局域网适配器 

            if ((item.NetworkInterfaceType == _type1) && item.OperationalStatus == OperationalStatus.Up)
            {
                foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                {
                    if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        output = ip.Address.ToString();
                    }
                }
            }
        }
        return output;
    }

三.操作:二:完成:亲测有效的,已经项目中使用了,but:在Unity2018.2版本后就弃用了

1.版本

  1. unity2017.4.35
  2. VS2017
  3. windows10 64位

1.代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyIPAddress : MonoBehaviour
{
    /// <summary>string:本机IP地址,电脑上面除wifi以外的适配器都禁用</summary>
    [Tooltip("string:本机IP地址")]
    [Header("string:本机IP地址")]
    [HideInInspector]
    public string str_ipAddress = "";

    // Use this for initialization
    void Start()
    {
      //  Debug.Log(Network.player.ipAddress);
    }

    // Update is called once per frame
    void Update()
    {

    }

    /// <summary>
    /// 功能: 设置获取本机IP地址
    /// </summary>
    public string SetGet_str_ipAddress
    {
        set { str_ipAddress = value; }
        get
        {
            str_ipAddress = Network.player.ipAddress;
            return str_ipAddress;
        }
    }

}