diff --git a/UserClass/GetLocalIP.cs b/UserClass/GetLocalIP.cs new file mode 100644 index 0000000..63c0a0f --- /dev/null +++ b/UserClass/GetLocalIP.cs @@ -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地址"; + } + + } +} diff --git a/ViewModel/MainWindowViewModel.cs b/ViewModel/MainWindowViewModel.cs index 3594401..b97900c 100644 --- a/ViewModel/MainWindowViewModel.cs +++ b/ViewModel/MainWindowViewModel.cs @@ -96,7 +96,8 @@ namespace SunlightAggregationManager.ViewModel } catch (Exception) { P2 = 7790; } - using var _ = AsyncTcpServer.TcpMain(P1,P2); + Console.WriteLine(GetLocalIP.GetLocalIPv4Address().ToString()); + _ = AsyncTcpServer.TcpMain(P1,P2); } }