Best way to programmatically configure network ada

2019-01-08 23:10发布

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?

标签: c# .net wmi
5条回答
疯言疯语
2楼-- · 2019-01-08 23:36

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;
    }
查看更多
孤傲高冷的网名
3楼-- · 2019-01-08 23:41

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.

查看更多
相关推荐>>
4楼-- · 2019-01-08 23:42

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

https://github.com/kamran7679/ConfigureIP

查看更多
该账号已被封号
5楼-- · 2019-01-08 23:46

I can tell you the way the trojans do it, after having 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 atested to by anyone who has ever been infected and can no longer get to windowsupdate.com, mcafee.com etc.

查看更多
Explosion°爆炸
6楼-- · 2019-01-08 23:47

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();
查看更多
登录 后发表回答