在 .NET 中以编程方式配置网络适配器的最佳方法

发布于 2024-07-15 19:22:49 字数 204 浏览 2 评论 0原文

我有一个用 C# 编写的应用程序,需要能够在 Windows 中配置网络适配器。 我基本上通过 WMI 进行工作,但该解决方案有一些我不喜欢的地方:有时设置似乎不固定,并且当未插入网络电缆时,从 WMI 返回错误方法,所以我无法判断他们是否真的成功了。

我需要能够通过网络连接 - 属性 - TCP/IP 屏幕配置所有可用的设置。

最好的方法是什么?

I have an application written in C# that needs to be able to configure the network adapters in Windows. I have this basically working through WMI, but there are a couple of things I don't like about that solution: sometimes the settings don't seem to stick, and when the network cable is not plugged in, errors are returned from the WMI methods, so I can't tell if they really succeeded or not.

I need to be able to configure all of the settings available through the network connections - Properties - TCP/IP screens.

What's the best way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

何时共饮酒 2024-07-22 19:22:49

您可以使用 Process 触发 netsh 命令来设置所有属性在网络对话框中。

例如:
要在适配器上设置静态 ip 地址

netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.1 1

要将其设置为 dhcp,您可以使用

netsh interface ip set address "Local Area Connection" dhcp

从 C# 执行此操作 将

Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1");
p.StartInfo = psi;
p.Start();

设置为静态 可能需要几秒钟才能完成,因此如果需要,请确保等待该过程出口。

You could use Process to fire off netsh commands to set all the properties in the network dialogs.

eg:
To set a static ipaddress on an adapter

netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.1 1

To set it to dhcp you'd use

netsh interface ip set address "Local Area Connection" dhcp

To do it from C# would be

Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1");
p.StartInfo = psi;
p.Start();

Setting to static can take a good couple of seconds to complete so if you need to, make sure you wait for the process to exit.

第七度阳光i 2024-07-22 19:22:49

用我的代码
SetIpAddress 和 SetDHCP

    /// <summary>
    /// Sets the ip address.
    /// </summary>
    /// <param name="nicName">Name of the nic.</param>
    /// <param name="ipAddress">The ip address.</param>
    /// <param name="subnetMask">The subnet mask.</param>
    /// <param name="gateway">The gateway.</param>
    /// <param name="dns1">The DNS1.</param>
    /// <param name="dns2">The DNS2.</param>
    /// <returns></returns>
    public static bool SetIpAddress(
        string nicName,
        string ipAddress,
        string subnetMask,
        string gateway = null,
        string dns1 = null,
        string dns2 = null)
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
        string nicDesc = nicName;

        if (networkInterface != null)
        {
            nicDesc = networkInterface.Description;
        }

        foreach (ManagementObject mo in moc)
        {
            if ((bool)mo["IPEnabled"] == true
                && mo["Description"].Equals(nicDesc) == true)
            {
                try
                {
                    ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");

                    newIP["IPAddress"] = new string[] { ipAddress };
                    newIP["SubnetMask"] = new string[] { subnetMask };

                    ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);

                    if (gateway != null)
                    {
                        ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");

                        newGateway["DefaultIPGateway"] = new string[] { gateway };
                        newGateway["GatewayCostMetric"] = new int[] { 1 };

                        ManagementBaseObject setGateway = mo.InvokeMethod("SetGateways", newGateway, null);
                    }


                    if (dns1 != null || dns2 != null)
                    {
                        ManagementBaseObject newDns = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        var dns = new List<string>();

                        if (dns1 != null)
                        {
                            dns.Add(dns1);
                        }

                        if (dns2 != null)
                        {
                            dns.Add(dns2);
                        }

                        newDns["DNSServerSearchOrder"] = dns.ToArray();

                        ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
                    }
                }
                catch
                {
                    return false;
                }
            }
        }

        return true;
    }

    /// <summary>
    /// Sets the DHCP.
    /// </summary>
    /// <param name="nicName">Name of the nic.</param>
    public static bool SetDHCP(string nicName)
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
        string nicDesc = nicName;

        if (networkInterface != null)
        {
            nicDesc = networkInterface.Description;
        }

        foreach (ManagementObject mo in moc)
        {
            if ((bool)mo["IPEnabled"] == true
                && mo["Description"].Equals(nicDesc) == true)
            {
                try
                {
                    ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");

                    newDNS["DNSServerSearchOrder"] = null;
                    ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
                    ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                }
                catch
                {
                    return false;
                }
            }
        }

        return true;
    }

With my code
SetIpAddress and SetDHCP

    /// <summary>
    /// Sets the ip address.
    /// </summary>
    /// <param name="nicName">Name of the nic.</param>
    /// <param name="ipAddress">The ip address.</param>
    /// <param name="subnetMask">The subnet mask.</param>
    /// <param name="gateway">The gateway.</param>
    /// <param name="dns1">The DNS1.</param>
    /// <param name="dns2">The DNS2.</param>
    /// <returns></returns>
    public static bool SetIpAddress(
        string nicName,
        string ipAddress,
        string subnetMask,
        string gateway = null,
        string dns1 = null,
        string dns2 = null)
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
        string nicDesc = nicName;

        if (networkInterface != null)
        {
            nicDesc = networkInterface.Description;
        }

        foreach (ManagementObject mo in moc)
        {
            if ((bool)mo["IPEnabled"] == true
                && mo["Description"].Equals(nicDesc) == true)
            {
                try
                {
                    ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");

                    newIP["IPAddress"] = new string[] { ipAddress };
                    newIP["SubnetMask"] = new string[] { subnetMask };

                    ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);

                    if (gateway != null)
                    {
                        ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");

                        newGateway["DefaultIPGateway"] = new string[] { gateway };
                        newGateway["GatewayCostMetric"] = new int[] { 1 };

                        ManagementBaseObject setGateway = mo.InvokeMethod("SetGateways", newGateway, null);
                    }


                    if (dns1 != null || dns2 != null)
                    {
                        ManagementBaseObject newDns = mo.GetMethodParameters("SetDNSServerSearchOrder");
                        var dns = new List<string>();

                        if (dns1 != null)
                        {
                            dns.Add(dns1);
                        }

                        if (dns2 != null)
                        {
                            dns.Add(dns2);
                        }

                        newDns["DNSServerSearchOrder"] = dns.ToArray();

                        ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
                    }
                }
                catch
                {
                    return false;
                }
            }
        }

        return true;
    }

    /// <summary>
    /// Sets the DHCP.
    /// </summary>
    /// <param name="nicName">Name of the nic.</param>
    public static bool SetDHCP(string nicName)
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
        string nicDesc = nicName;

        if (networkInterface != null)
        {
            nicDesc = networkInterface.Description;
        }

        foreach (ManagementObject mo in moc)
        {
            if ((bool)mo["IPEnabled"] == true
                && mo["Description"].Equals(nicDesc) == true)
            {
                try
                {
                    ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");

                    newDNS["DNSServerSearchOrder"] = null;
                    ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null);
                    ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                }
                catch
                {
                    return false;
                }
            }
        }

        return true;
    }
眼前雾蒙蒙 2024-07-22 19:22:49

在 @PaulB 的回答帮助下

NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address " + nics[0].Name + " static 192.168." + provider_ip + "." + index + " 255.255.255.0 192.168." + provider_ip + ".1 1");
p.StartInfo = psi;
p.StartInfo.Verb = "runas";
p.Start();

with the help of @PaulB's answers help

NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address " + nics[0].Name + " static 192.168." + provider_ip + "." + index + " 255.255.255.0 192.168." + provider_ip + ".1 1");
p.StartInfo = psi;
p.StartInfo.Verb = "runas";
p.Start();
一百个冬季 2024-07-22 19:22:49

我可以告诉你木马的做法,在清理了几次之后,就是在 HKEY_LOCAL_MACHINE 下设置注册表项。 他们设置的主要方法是 DNS 方法,这种方法绝对有效,任何曾经被感染并且无法再访问 windowsupdate.com、mcafee.com 等的人都可以证明这一点。

I can tell you the way the trojans do it, after having had to clean up after a few of them, is to set registry keys under HKEY_LOCAL_MACHINE. The main ones they set are the DNS ones and that approach definitely sticks which can be attested to by anyone who has ever been infected and can no longer get to windowsupdate.com, mcafee.com, etc.

北城孤痞 2024-07-22 19:22:49

看看这个应用程序。 这是一个完整的应用程序,用于设置 wifi 和以太网 ip

https://github.com/kamran7679/ConfigureIP

Checkout this app. it is a complete application to set both wifi and ethernet ips

https://github.com/kamran7679/ConfigureIP

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文