You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
2.1 KiB
53 lines
2.1 KiB
|
3 months ago
|
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地址";
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|
||
|
|
}
|