You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace PrintBarCode.Helper
{
public class NetworkHelper
{
/// <summary>
/// 获取本地计算机的所有 IPv4 地址。
/// </summary>
/// <returns>IPv4 地址列表。如果没有找到,则返回一个空列表。</returns>
public static List<string> GetLocalIPv4Addresses()
{
List<string> ipAddresses = new List<string>();
try
{
// 获取所有网络接口
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var networkInterface in networkInterfaces)
{
// 检查网络接口是否处于正常状态且不是回环接口
if (networkInterface.OperationalStatus == OperationalStatus.Up &&
networkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
// 获取该接口的IP属性
var ipProperties = networkInterface.GetIPProperties();
// 获取单播地址集合
var unicastAddresses = ipProperties.UnicastAddresses;
foreach (var address in unicastAddresses)
{
// 检查是否是 IPv4 地址
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
{
// 获取 IPv4 地址并添加到列表
var ipAddress = address.Address.ToString();
if (!string.IsNullOrEmpty(ipAddress) && !ipAddress.StartsWith("169.254")) // 排除自动私有地址
{
ipAddresses.Add(ipAddress);
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("获取IP地址时发生错误: " + ex.Message);
}
return ipAddresses;
}
/// <summary>
/// 获取本地计算机的第一个有效的 IPv4 地址。
/// </summary>
/// <returns>第一个有效的 IPv4 地址,如果没有找到则返回 null。</returns>
public static string GetFirstLocalIPv4Address()
{
var ipAddresses = GetLocalIPv4Addresses();
return ipAddresses.Count > 0 ? ipAddresses[0] : null;
}
}
}