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);