C#代码实现网口配置:获取与设置网卡信息

在网络编程中,我们经常需要获取或设置网口的配置信息,例如IP地址、子网掩码、默认网关等。本文将介绍如何使用C#代码实现网口配置,并提供完整的代码示例。

获取网卡信息

要获取网卡信息,可以使用 System.Net.NetworkInformation 命名空间中的类和方法。以下代码演示如何获取所有网卡接口,并打印出每个网卡的名称、描述、IP地址、子网掩码和默认网关:csharpusing System;using System.Net.NetworkInformation;using System.Net.Sockets;

class Program{ static void Main(string[] args) { // 获取所有的网卡接口 NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

    // 遍历每个网卡接口        foreach (NetworkInterface adapter in interfaces)        {            // 忽略非以太网接口和回环接口            if (adapter.NetworkInterfaceType != NetworkInterfaceType.Ethernet && adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback)                continue;

        Console.WriteLine('网卡名称: ' + adapter.Name);            Console.WriteLine('网卡描述: ' + adapter.Description);

        // 获取网卡的 IP 配置信息            IPInterfaceProperties ipProperties = adapter.GetIPProperties();            foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses)            {                Console.WriteLine('IP 地址: ' + ip.Address.ToString());                Console.WriteLine('子网掩码: ' + ip.IPv4Mask.ToString());            }

        // 获取网卡的默认网关            foreach (GatewayIPAddressInformation gateway in ipProperties.GatewayAddresses)            {                Console.WriteLine('默认网关: ' + gateway.Address.ToString());            }

        Console.WriteLine();        }

    Console.ReadLine();    }}

设置网卡的IP地址和子网掩码

以下代码演示如何设置第一个网卡接口的IP地址和子网掩码:csharp// ... (获取网卡接口代码,参考上一节) ...

// 设置网卡的 IP 地址和子网掩码NetworkInterface selectedAdapter = interfaces[0];IPAddress newIpAddress = IPAddress.Parse('192.168.0.100');IPAddress newSubnetMask = IPAddress.Parse('255.255.255.0');IPInterfaceProperties selectedIpProperties = selectedAdapter.GetIPProperties();selectedIpProperties.UnicastAddresses[0].IPv4Mask = newSubnetMask;selectedIpProperties.UnicastAddresses[0].Address = newIpAddress;selectedAdapter.SetIPProperties(selectedIpProperties);

Console.WriteLine('网卡配置已更新');

// ...

注意事项

  • 在实际应用中,需要确保应用程序具有足够的权限才能访问和修改网口配置。* 修改网卡配置可能会导致网络连接中断,请谨慎操作。

希望本文能帮助您使用C#代码实现网口配置。如果您有任何问题,请随时留言。

C#代码实现网口配置:获取与设置网卡信息

原文地址: https://www.cveoy.top/t/topic/T7Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录