【问题标题】:Best way to programmatically configure network adapters in .NET在 .NET 中以编程方式配置网络适配器的最佳方式
【发布时间】:2010-10-15 21:51:21
【问题描述】:

我有一个用 C# 编写的应用程序,它需要能够在 Windows 中配置网络适配器。我基本上通过 WMI 来解决这个问题,但是我不喜欢该解决方案的一些事情:有时设置似乎不固定,并且当未插入网络电缆时,WMI 会返回错误方法,所以我不知道他们是否真的成功了。

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

最好的方法是什么?

【问题讨论】:

    标签: c# .net wmi


    【解决方案1】:

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

    【讨论】:

    • "HKEY_LOCAL_MACHINE" 并没有完全缩小找到重要密钥的位置。更多细节将使这个答案真正有用。
    【解决方案2】:

    使用我的代码 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;
        }
    

    【讨论】:

      【解决方案3】:

      查看此应用。这是一个设置wifi和以太网ips的完整应用程序

      https://github.com/kamran7679/ConfigureIP

      【讨论】:

        【解决方案4】:

        借助@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();
        

        【讨论】:

          【解决方案5】:

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

          例如: 在适配器上设置静态 ipaddress

          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();
          

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

          【讨论】:

          • 知道如何提升此命令以使用管理员权限运行吗?
          • 这个答案的一个缺点是您的网卡名称并不总是“本地连接”,它可能会有所不同。
          • @MubasharAhmad 解决此问题的一种方法是使用 NetworkInterface 获取所有带有“.Description”的接口名称,然后让他们从中进行选择。然后,获取“.Name”并将其传递给命令字符串。至少,我就是这么做的。
          • 如何在同一个ProcessStartInfo中设置静态DNS
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-18
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多