2009-03-27 6 views
18

Ho un'applicazione scritta in C# che deve essere in grado di configurare gli adattatori di rete in Windows. Ho fondamentalmente questo lavoro tramite WMI, ma ci sono un paio di cose che non mi piacciono di questa soluzione: a volte le impostazioni non sembrano attaccare, e quando il cavo di rete non è collegato, gli errori vengono restituiti dal WMI metodi, quindi non posso dire se ci sono riusciti o meno.Il modo migliore per configurare in modo programmatico gli adattatori di rete in .NET

Devo essere in grado di configurare tutte le impostazioni disponibili tramite le connessioni di rete - Proprietà - Schermate TCP/IP.

Qual è il modo migliore per farlo?

risposta

21

È possibile utilizzare Process per attivare i comandi netsh per impostare tutte le proprietà nelle finestre di dialogo di rete.

esempio: Per impostare un IP address statico su un adattatore

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

per impostarlo su DHCP usereste

netsh interface ip set address "Local Area Connection" dhcp 

Per farlo da C# sarebbe

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

L'impostazione su statico può richiedere un paio di secondi per completare, quindi se è necessario, assicurati di attendere per il processo di uscita.

+0

Qualche idea su come elevare questo comando per essere eseguito con le autorizzazioni di amministratore? – Fuser97381

+0

Dai un'occhiata a http://stackoverflow.com/questions/133379/elevating-process-privileg-programatically – PaulB

+0

Grazie, sei il migliore. – Fuser97381

2

Posso dire che il modo in cui i trojan lo fanno, dopo aver pulito dopo alcuni di loro, è impostare le chiavi di registro in HKEY_LOCAL_MACHINE. I principali sono quelli DNS e questo approccio è decisamente valido e può essere verificato da chiunque sia mai stato infettato e non può più accedere a windowsupdate.com, mcafee.com ecc.

+0

"HKEY_LOCAL_MACHINE" non esattamente restringere il campo dove trovare le chiavi che contano . Un po 'più di dettaglio renderebbe questa risposta effettivamente utile. – mickeyf

0

con l'aiuto di risposte di @ paulb aiutare

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

con il mio codice SetIpAddress e 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; 
    } 
Problemi correlati