using System.Net; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Peripherals.NetConfigClient; namespace server.Controllers; /// /// 网络配置控制器(仅管理员权限) /// [ApiController] [Route("api/[controller]")] [Authorize("Admin")] public class NetConfigController : ControllerBase { private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); // 固定的实验板IP,端口,MAC地址 private const string BOARD_IP = "169.254.109.0"; private const int BOARD_PORT = 1234; // 本机网络信息 private readonly IPAddress _localIP; private readonly byte[] _localMAC; private readonly string _localIPString; private readonly string _localMACString; private readonly string _localInterface; public NetConfigController() { // 初始化本机IP地址 _localIP = GetLocalIPAddress(); _localIPString = _localIP?.ToString() ?? "未知"; // 初始化本机MAC地址 _localMAC = GetLocalMACAddress(); _localMACString = _localMAC != null ? BitConverter.ToString(_localMAC).Replace("-", ":") : "未知"; // 获取本机网络接口名称 _localInterface = GetLocalNetworkInterface(); logger.Info($"NetConfigController 初始化完成 - 本机IP: {_localIPString}, 本机MAC: {_localMACString}, 接口: {_localInterface}"); } /// /// 获取本机IP地址(优先选择与实验板同网段的IP) /// /// 本机IP地址 private IPAddress GetLocalIPAddress() { try { var boardIpSegments = BOARD_IP.Split('.').Take(3).ToArray(); // 优先选择与实验板IP前三段相同的IP var sameSegmentIP = System.Net.NetworkInformation.NetworkInterface .GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback) .SelectMany(nic => nic.GetIPProperties().UnicastAddresses) .Where(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) .Select(addr => addr.Address) .FirstOrDefault(addr => { var segments = addr.ToString().Split('.'); return segments.Length == 4 && segments[0] == boardIpSegments[0] && segments[1] == boardIpSegments[1] && segments[2] == boardIpSegments[2]; }); if (sameSegmentIP != null) return sameSegmentIP; // 如果没有找到同网段的IP,返回第一个可用的IP return System.Net.NetworkInformation.NetworkInterface .GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback) .SelectMany(nic => nic.GetIPProperties().UnicastAddresses) .Where(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) .Select(addr => addr.Address) .FirstOrDefault() ?? IPAddress.Loopback; } catch (Exception ex) { logger.Error(ex, "获取本机IP地址失败"); return IPAddress.Loopback; } } /// /// 获取本机MAC地址 /// /// 本机MAC地址字节数组 private byte[] GetLocalMACAddress() { try { return System.Net.NetworkInformation.NetworkInterface .GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback) .Select(nic => nic.GetPhysicalAddress()?.GetAddressBytes()) .FirstOrDefault(bytes => bytes != null && bytes.Length == 6) ?? new byte[6]; } catch (Exception ex) { logger.Error(ex, "获取本机MAC地址失败"); return new byte[6]; } } /// /// 获取本机网络接口名称 /// /// 网络接口名称 private string GetLocalNetworkInterface() { return GetLocalIPAddress().ToString(); } /// /// 初始化ARP记录 /// /// 是否成功 private async Task InitializeArpAsync() { try { return await ArpClient.UpdateArpEntryAsync(BOARD_IP); } catch (Exception ex) { logger.Error(ex, "初始化ARP记录失败"); return false; } } /// /// 获取主机IP地址 /// /// 主机IP地址 [HttpGet("GetHostIP")] [EnableCors("Users")] [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetHostIP() { try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.GetHostIP(); if (!result.IsSuccessful) { logger.Error($"获取主机IP失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"获取失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "获取主机IP时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "获取失败,请稍后重试"); } } /// /// 获取板卡IP地址 /// /// 板卡IP地址 [HttpGet("GetBoardIP")] [EnableCors("Users")] [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetBoardIP() { try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.GetBoardIP(); if (!result.IsSuccessful) { logger.Error($"获取板卡IP失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"获取失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "获取板卡IP时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "获取失败,请稍后重试"); } } /// /// 获取主机MAC地址 /// /// 主机MAC地址 [HttpGet("GetHostMAC")] [EnableCors("Users")] [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetHostMAC() { try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.GetHostMAC(); if (!result.IsSuccessful) { logger.Error($"获取主机MAC地址失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"获取失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "获取主机MAC地址时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "获取失败,请稍后重试"); } } /// /// 获取板卡MAC地址 /// /// 板卡MAC地址 [HttpGet("GetBoardMAC")] [EnableCors("Users")] [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetBoardMAC() { try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.GetBoardMAC(); if (!result.IsSuccessful) { logger.Error($"获取板卡MAC地址失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"获取失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "获取板卡MAC地址时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "获取失败,请稍后重试"); } } /// /// 获取所有网络配置信息 /// /// 网络配置信息 [HttpGet("GetNetworkConfig")] [EnableCors("Users")] [ProducesResponseType(typeof(NetworkConfigDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task GetNetworkConfig() { try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var hostIPResult = await netConfig.GetHostIP(); var boardIPResult = await netConfig.GetBoardIP(); var hostMACResult = await netConfig.GetHostMAC(); var boardMACResult = await netConfig.GetBoardMAC(); var config = new NetworkConfigDto { HostIP = hostIPResult.IsSuccessful ? hostIPResult.Value : "获取失败", BoardIP = boardIPResult.IsSuccessful ? boardIPResult.Value : "获取失败", HostMAC = hostMACResult.IsSuccessful ? hostMACResult.Value : "获取失败", BoardMAC = boardMACResult.IsSuccessful ? boardMACResult.Value : "获取失败" }; return Ok(config); } catch (Exception ex) { logger.Error(ex, "获取网络配置信息时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "获取失败,请稍后重试"); } } /// /// 获取本机所有网络接口信息 /// /// 网络接口信息列表 [HttpGet("GetLocalNetworkInterfaces")] [EnableCors("Users")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public IActionResult GetLocalNetworkInterfaces() { try { var interfaces = System.Net.NetworkInformation.NetworkInterface .GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && nic.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback) .Select(nic => new NetworkInterfaceDto { Name = nic.Name, Description = nic.Description, Type = nic.NetworkInterfaceType.ToString(), Status = nic.OperationalStatus.ToString(), IPAddresses = nic.GetIPProperties().UnicastAddresses .Where(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) .Select(addr => addr.Address.ToString()) .ToList(), MACAddress = nic.GetPhysicalAddress().ToString() }) .ToList(); return Ok(interfaces); } catch (Exception ex) { logger.Error(ex, "获取本机网络接口信息时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "获取失败,请稍后重试"); } } /// /// 设置主机IP地址 /// /// 主机IP地址 /// 操作结果 [HttpPost("SetHostIP")] [EnableCors("Users")] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task SetHostIP(string hostIp) { if (string.IsNullOrWhiteSpace(hostIp)) return BadRequest("主机IP地址不能为空"); if (!IPAddress.TryParse(hostIp, out var hostIpAddress)) return BadRequest("主机IP地址格式不正确"); try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.SetHostIP(hostIpAddress); if (!result.IsSuccessful) { logger.Error($"设置主机IP失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"设置失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "设置主机IP时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "设置失败,请稍后重试"); } } /// /// 设置板卡IP地址 /// /// 新的板卡IP地址 /// 操作结果 [HttpPost("SetBoardIP")] [EnableCors("Users")] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task SetBoardIP(string newBoardIp) { if (string.IsNullOrWhiteSpace(newBoardIp)) return BadRequest("新的板卡IP地址不能为空"); if (!IPAddress.TryParse(newBoardIp, out var newIpAddress)) return BadRequest("新的板卡IP地址格式不正确"); try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.SetBoardIP(newIpAddress); if (!result.IsSuccessful) { logger.Error($"设置板卡IP失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"设置失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "设置板卡IP时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "设置失败,请稍后重试"); } } /// /// 设置板卡MAC地址 /// /// 板卡MAC地址(格式:AA:BB:CC:DD:EE:FF) /// 操作结果 [HttpPost("SetBoardMAC")] [EnableCors("Users")] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task SetBoardMAC(string boardMac) { if (string.IsNullOrWhiteSpace(boardMac)) return BadRequest("板卡MAC地址不能为空"); // 解析MAC地址 if (!TryParseMacAddress(boardMac, out var macBytes)) return BadRequest("MAC地址格式不正确,请使用格式:AA:BB:CC:DD:EE:FF"); try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } // 创建网络配置客户端 var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.SetBoardMAC(macBytes); if (!result.IsSuccessful) { logger.Error($"设置板卡MAC地址失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"设置失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "设置板卡MAC地址时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "设置失败,请稍后重试"); } } /// /// 设置主机MAC地址 /// /// 主机MAC地址(格式:AA:BB:CC:DD:EE:FF) /// 操作结果 [HttpPost("SetHostMAC")] [EnableCors("Users")] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task SetHostMAC(string hostMac) { if (string.IsNullOrWhiteSpace(hostMac)) return BadRequest("主机MAC地址不能为空"); // 解析MAC地址 if (!TryParseMacAddress(hostMac, out var macBytes)) return BadRequest("MAC地址格式不正确,请使用格式:AA:BB:CC:DD:EE:FF"); try { if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.SetHostMAC(macBytes); if (!result.IsSuccessful) { logger.Error($"设置主机MAC地址失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"设置失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "设置主机MAC地址时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "设置失败,请稍后重试"); } } /// /// 自动获取本机IP地址并设置为实验板主机IP /// /// 操作结果 [HttpPost("UpdateHostIP")] [EnableCors("Users")] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task UpdateHostIP() { try { if (_localIP == null) return StatusCode(StatusCodes.Status500InternalServerError, "无法获取本机IP地址"); if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.SetHostIP(_localIP); if (!result.IsSuccessful) { logger.Error($"自动设置主机IP失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"设置失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "自动设置主机IP时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "设置失败,请稍后重试"); } } /// /// 更新主机MAC地址 /// /// 操作结果 [HttpPost("UpdateHostMAC")] [EnableCors("Users")] [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public async Task UpdateHostMAC() { try { if (_localMAC == null || _localMAC.Length != 6) return StatusCode(StatusCodes.Status500InternalServerError, "无法获取本机MAC地址"); if (!(await InitializeArpAsync())) { throw new Exception("无法配置ARP记录"); } var netConfig = new NetConfig(BOARD_IP, BOARD_PORT, 0); var result = await netConfig.SetHostMAC(_localMAC); if (!result.IsSuccessful) { logger.Error($"设置主机MAC地址失败: {result.Error}"); return StatusCode(StatusCodes.Status500InternalServerError, $"设置失败: {result.Error}"); } return Ok(result.Value); } catch (Exception ex) { logger.Error(ex, "设置主机MAC地址时发生异常"); return StatusCode(StatusCodes.Status500InternalServerError, "设置失败,请稍后重试"); } } /// /// 获取本机网络信息 /// /// 本机网络信息 [HttpGet("GetLocalNetworkInfo")] [EnableCors("Users")] [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] public IActionResult GetLocalNetworkInfo() { return Ok(new { LocalIP = _localIPString, LocalMAC = _localMACString, LocalInterface = _localInterface }); } /// /// 解析MAC地址字符串为字节数组 /// /// MAC地址字符串 /// 解析后的字节数组 /// 是否解析成功 private static bool TryParseMacAddress(string macAddress, out byte[] macBytes) { macBytes = Array.Empty(); if (string.IsNullOrWhiteSpace(macAddress)) return false; // 移除可能的分隔符并统一为冒号 var cleanMac = macAddress.Replace("-", ":").Replace(" ", "").ToUpper(); // 验证格式 if (cleanMac.Length != 17 || cleanMac.Count(c => c == ':') != 5) return false; var parts = cleanMac.Split(':'); if (parts.Length != 6) return false; try { macBytes = new byte[6]; for (int i = 0; i < 6; i++) { macBytes[i] = Convert.ToByte(parts[i], 16); } return true; } catch { macBytes = Array.Empty(); return false; } } } /// /// 网络配置数据传输对象 /// public class NetworkConfigDto { /// /// 主机IP地址 /// public string? HostIP { get; set; } /// /// 板卡IP地址 /// public string? BoardIP { get; set; } /// /// 主机MAC地址 /// public string? HostMAC { get; set; } /// /// 板卡MAC地址 /// public string? BoardMAC { get; set; } } /// /// 网络配置操作结果 /// public class NetworkConfigResult { /// /// 主机IP设置结果 /// public bool? HostIPResult { get; set; } /// /// 主机IP设置错误信息 /// public string? HostIPError { get; set; } /// /// 板卡IP设置结果 /// public bool? BoardIPResult { get; set; } /// /// 板卡IP设置错误信息 /// public string? BoardIPError { get; set; } /// /// 主机MAC设置结果 /// public bool? HostMACResult { get; set; } /// /// 主机MAC设置错误信息 /// public string? HostMACError { get; set; } /// /// 板卡MAC设置结果 /// public bool? BoardMACResult { get; set; } /// /// 板卡MAC设置错误信息 /// public string? BoardMACError { get; set; } } /// /// 网络接口信息数据传输对象 /// public class NetworkInterfaceDto { /// /// 网络接口名称 /// public string Name { get; set; } = string.Empty; /// /// 网络接口描述 /// public string Description { get; set; } = string.Empty; /// /// 网络接口类型 /// public string Type { get; set; } = string.Empty; /// /// 网络接口状态 /// public string Status { get; set; } = string.Empty; /// /// IP地址列表 /// public List IPAddresses { get; set; } = new(); /// /// MAC地址 /// public string MACAddress { get; set; } = string.Empty; }