fix: 修复获取主机ip错误的问题

This commit is contained in:
2025-07-18 12:28:32 +08:00
parent 12cd35edff
commit e9ad1f0256
2 changed files with 67 additions and 3 deletions

View File

@@ -153,7 +153,7 @@ public class NetConfigController : ControllerBase
try
{
var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0);
var hostIPResult = await netConfig.GetHostIP();
var boardIPResult = await netConfig.GetBoardIP();
var hostMACResult = await netConfig.GetHostMAC();
@@ -345,7 +345,8 @@ public class NetConfigController : ControllerBase
{
try
{
// 获取本机第一个有效的IPv4地址
// 获取所有本机IPv4地址并选择与实验板IP前三段相同的IP
var boardIpSegments = BOARD_IP.Split('.').Take(3).ToArray();
var ip = System.Net.NetworkInformation.NetworkInterface
.GetAllNetworkInterfaces()
.Where(nic => nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up
@@ -353,7 +354,14 @@ public class NetConfigController : ControllerBase
.SelectMany(nic => nic.GetIPProperties().UnicastAddresses)
.Where(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
.Select(addr => addr.Address)
.FirstOrDefault();
.FirstOrDefault(addr =>
{
var segments = addr.ToString().Split('.');
return segments.Length == 4 &&
segments[0] == boardIpSegments[0] &&
segments[1] == boardIpSegments[1] &&
segments[2] == boardIpSegments[2];
});
if (ip == null)
return StatusCode(StatusCodes.Status500InternalServerError, "无法获取本机IP地址");