添加ip获取
This commit is contained in:
commit
650c7c47d9
2 files changed
+54
-1
No files matched your search
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace SunlightAggregationManager.UserClass
|
||||
{
|
||||
public class GetLocalIP
|
||||
{
|
||||
public static string GetLocalIPv4Address()
|
||||
{
|
||||
// 获取所有网络接口
|
||||
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
|
||||
|
||||
foreach (var ni in networkInterfaces)
|
||||
{
|
||||
// 筛选条件:
|
||||
// 1. 网卡状态为 Up (已连接)
|
||||
// 2. 排除虚拟网卡、回环网卡、隧道网卡
|
||||
// 3. 支持 IPv4
|
||||
if (ni.OperationalStatus == OperationalStatus.Up &&
|
||||
ni.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
|
||||
ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel &&
|
||||
!ni.Description.Contains("Virtual") && // 排除常见的虚拟网卡描述
|
||||
ni.Supports(NetworkInterfaceComponent.IPv4))
|
||||
{
|
||||
var ipProperties = ni.GetIPProperties();
|
||||
// 获取单播地址(即分配的 IP 地址)
|
||||
var unicastAddresses = ipProperties.UnicastAddresses;
|
||||
|
||||
foreach (var ua in unicastAddresses)
|
||||
{
|
||||
// 筛选出 IPv4 地址,且排除 127.0.0.1 回环地址
|
||||
if (ua.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ua.Address))
|
||||
{
|
||||
// 优先返回有默认网关的地址(通常是当前正在上网的主网卡)
|
||||
if (ipProperties.GatewayAddresses.Any(g => g.Address.AddressFamily == AddressFamily.InterNetwork))
|
||||
{
|
||||
return ua.Address.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return "未找到有效的局域网IPv4地址";
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user