Blame view

Yi.Abp.Net8/framework/Yi.Framework.Core/Helper/IpHelper.cs 1.71 KB
515fceeb   “wangming”   框架初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  using System.Linq;
  using System.Net;
  using System.Net.NetworkInformation;
  using System.Net.Sockets;
  
  namespace Yi.Framework.Core.Helper
  {
      public class IpHelper
      {
          /// <summary>
          /// 获取当前IP地址
          /// </summary>
          /// <param name="preferredNetworks"></param>
          /// <returns></returns>
          public static string GetCurrentIp(string preferredNetworks)
          {
              var instanceIp = "127.0.0.1";
  
              try
              {
                  // 获取可用网卡
                  var nics = NetworkInterface.GetAllNetworkInterfaces()?.Where(network => network.OperationalStatus == OperationalStatus.Up);
  
                  // 获取所有可用网卡IP信息
                  var ipCollection = nics?.Select(x => x.GetIPProperties())?.SelectMany(x => x.UnicastAddresses);
  
                  if (ipCollection is null)
                  {
                      return instanceIp;
                  }
  
                  foreach (var ipadd in ipCollection)
                  {
                      if (!IPAddress.IsLoopback(ipadd.Address) && ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
                      {
                          if (string.IsNullOrEmpty(preferredNetworks))
                          {
                              instanceIp = ipadd.Address.ToString();
                              break;
                          }
  
                          if (!ipadd.Address.ToString().StartsWith(preferredNetworks)) continue;
                          instanceIp = ipadd.Address.ToString();
                          break;
                      }
                  }
              }
              catch
              {
                  // ignored
              }
  
              return instanceIp;
          }
      }
  }