Josep Maria Vidal
Josep Maria Vidal

Reputation: 1

Set IP address of a network interface useing c# and .Net API without WMI

I'm a newcomer on .Net and c# programming. I'm trying to perform a small program to set up in a few clics the IP address of my local network card. (What I want to achieve is going faster than through the windows configuration menus) So I've made a little research and I found several nice examples that fits my needs. Anyway, I've realised that I can get a network device IP config via .Net namespaces (System.Net.Networkinformation...) but I can't set a new one (I mean, this API is full of getters but no setters) so, as far as I googled, to set an IP I must perform WMI calls. My question is if there is a method to do it via .Net (I didn't found it by de moment). Thanks in advance!

Upvotes: 0

Views: 1683

Answers (1)

NicoRiff
NicoRiff

Reputation: 4883

You can use ORMi library as it is a WMI wrapper that makes WMI access simpler.

1) Define your class:

[WMIClass("Win32_NetworkAdapterConfiguration")]
public class NetworkAdapterConfiguration
{
    public int Index { get; set; } //YOU MUST SET THIS AS IT IS THE CIM_KEY OF THE CLASS
    public string Caption { get; set; }
    public string Description { get; set; }

    public uint IPConnectionMetric { get; set; }

    public UInt32 InterfaceIndex { get; set; }

    public string WINSScopeID { get; set; }

    public bool SetStatic(string ip, string netmask)
    {
        int retVal = WMIMethod.ExecuteMethod(this, new { IPAddress = new string[] { ip }, SubnetMask = new string[] { netmask } });

        if (retVal != 0)
            Console.WriteLine($"Failed to set network settings with error code {retVal}");

        return retVal == 0;
    }
}

2) Use:

        WMIHelper helper = new WMIHelper("root\\CimV2");

        NetworkAdapterConfiguration networkInterface = helper.Query<NetworkAdapterConfiguration>().ToList()
            .Where(n => n.Description == "Intel(R) Ethernet Connection").SingleOrDefault();

        networkInterface.SetStatic("192.168.0.35", "255.255.255.0");

Upvotes: 1

Related Questions