首页 > 编程语言 > 详细

unity 获取本地ip地址

时间:2019-10-15 16:41:28      阅读:479      评论:0      收藏:0      [点我收藏+]
 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using System.Net.NetworkInformation;
 4 using System.Net.Sockets;
 5 using UnityEngine;
 6 
 7 public class Ip 
 8 {
 9     public enum ADDRESSFAM
10     {
11         IPv4, IPv6
12     }
13     /// <summary>
14     /// 获取本机IP
15     /// </summary>
16     /// <param name="Addfam">要获取的IP类型</param>
17     /// <returns></returns>
18     public static string GetIP(ADDRESSFAM Addfam)
19     {
20         if (Addfam == ADDRESSFAM.IPv6 && !Socket.OSSupportsIPv6)
21         {
22             return null;
23         }
24         string output = "";
25         foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
26         {
27 #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
28             NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
29             NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
30 
31             if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
32 #endif 
33             {
34                 foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
35                 {
36                     //IPv4
37                     if (Addfam == ADDRESSFAM.IPv4)
38                     {
39                         if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
40                         {
41                             output = ip.Address.ToString();
42                             //Debug.Log("IP:" + output);
43                         }
44                     }
45 
46                     //IPv6
47                     else if (Addfam == ADDRESSFAM.IPv6)
48                     {
49                         if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
50                         {
51                             output = ip.Address.ToString();
52                         }
53                     }
54                 }
55             }
56         }
57         return output;
58     }
59 
60 }

 

调用方法     string ip=Ip.GetIP(ADDRESSFAM.IPv4);

 

unity 获取本地ip地址

原文:https://www.cnblogs.com/G993/p/11678584.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!