2

I'm having an issue where my code is setting Static IP and DHCP perfectly fine when I'm connected to the WiFi. However, the Ethernet "local networkinterface" is unchangable, when no cable is connected. The issue is vice-versa for when connected with cable, and trying to set the WiFi interface.

The issue seem to only be present when the interface is disconnected and have no live connection. Anyone else able to reproduce? innput nicName is the name of interface I'm sending from my Form, and is basically used for matching it to the interfaceI want to change

Set StaticIP:

public static bool SetStaticIp(
    string nicName,
    Object objSite )
{
    Site site = (Site)objSite;
    //string nicName = adapter.Description;
    string ipAddress = $"{site.IP}";
    string subnetMask = $"{site.SubnetMask}";
    string gateway = $"{site.Gateway}";
    string dns1 = $"{site.Dns1}";
    string dns2 = $"{site.Dns2}";
    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)
    {
        bool moIpEnable = (bool)mo["IPEnabled"];
        string moDesc = (string)mo["Description"];

        if (moDesc.Equals(nicName) == 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 (Exception err)
            {

                Log(LOG_FN.ERROR, $"SetStaticIp({nicDesc}): Klarte ikke sette statisk IP. {err.Message}");
                return false;
            } 
        }
    }

    return true;
}

Set DHCP

 public static int SetDHCP(string nicName)
        {
            //string nicName = sroGlobal.SelectedAdapters.Description;
            //string nicName = Name;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            NetworkInterface networkInterface = interfaces.FirstOrDefault(x => x.Name == nicName);
            ManagementObjectCollection networkCollection = mc.GetInstances();

            string nicDesc = nicName;

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

            foreach (ManagementObject mo in networkCollection)
            {
                bool moIpEnable = (bool)mo["IPEnabled"];
                string moDesc = (string)mo["Description"];

                if (string.Compare(moDesc, nicName,StringComparison.InvariantCultureIgnoreCase) == 0)
                { 
                    try
                    {
                        ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");

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

                        Log(LOG_FN.ERROR, $"SetDHCP({nicDesc}): Could'nt set DHCP. {err.Message}");
                        return -1;
                    }
                }
            }
            return 0; 
        }

edit 1: format error

Saetheer
  • 31
  • 5
  • DCHP the IP address has to be within the mask range and cannot be the same IP address as an existing IP. So often duplicate IP are assigned by DHCP. You can check for duplicates by disconnecting the machine from network and ping address. If a pin comes back then you know it is a duplicate. To check mask from cmd.exe >IPConfig/ALL. – jdweng Jun 16 '21 at 12:11
  • And what is the issue? – sticky bit Jun 16 '21 at 12:12
  • I want to "clear" IP settings from the interface. For instance, I have set the interface to static IP. Later at the office, I'm connected to the WiFi, and want to set det interface to DHCP again. – Saetheer Jun 16 '21 at 12:17
  • @jdweng I dont this the duplication is the issue. In the interface, properties, I essentialy wants to just "flip" the switch between "use following IP" to "Receive IP automatically". I can't find any documentation on this "specific" command either. – Saetheer Jun 17 '21 at 05:52
  • What you want to can lead to duplicate IP addresses in the network. turning DHCP off and keeping the same IP address is bad. When you have DHCP running on a network there is a range of IP addresses that are assigned for DHCP. Any fix IP needs to be outside the range. Just turning off DHCP will allow DHCP server to reassign the IP address. When using DHCP the IP address gets changed on a regular basis. I think you can enable DHCP using from cmd.exe >Netsh/? (the question mark for help). – jdweng Jun 17 '21 at 09:20
  • Thanks for the reply @jdweng. I see I've been unclear, but I dont want to "keep" the IP settings when changing from Static to DHCP. When enabling DHCP, I want the networks DHCP server to determen my the IP range. The script I'm making changes the interface of my network card to static and DHCP on the fly, between sites I'm wokring on. So I have a project spesicif static IP ranges for several different facilities I'm attending. Before I'm leaving back to the office, I usually turn the IP back to DHCP for the reason you clarify: Avoid IP conflict. – Saetheer Jun 24 '21 at 08:47
  • With your scheme how do you prevent two machines from getting the same static IP? When going to DCHP you must get a new IP every time you switch. And DCHP may not get updated immediately from what I've seen. At work in the past, I've seen cases where we had to wait 24 hours to renew the IP. – jdweng Jun 24 '21 at 10:31
  • @jdweng There are no "safe guard" to prevent two machines from getting same static IP. The sites I'm working on have only static IPs, and I only want to change to DHCP before I'm heading back to the office to avoid IP conflict there. The issue is not preventing IP conflict, I'm intereseting in setting the TCP/IPv4 properties from 'Use the following IP address' to 'Obtain an IP address automatically'. I can do this manually, but not by code. – Saetheer Jul 01 '21 at 13:16
  • You need to use IPCONFIG. See options with help IPCONFIG/?. The renew option will update IP but could take up to 24 hours. You also have to make sure the DHCP range of address and separate from the Static Address to prevent duplicates. Most Networks have both DHCP and Static devices. I've seen too many times where more than one device gets assigned the same IP. – jdweng Jul 01 '21 at 15:06

0 Answers0