Estoy intentando crear una herramienta que convierta la dirección IPv4 proporcionada por DHCP, gateway y dns-settings en configuración estática. Intenté usar WMI para resolver este rompecabezas, pero tengo un problema que no puedo resolver.Problemas con el método WMI EnableStatic
La aplicación completa, DNS y Gateway está configurado, pero el EnableStatic
método (para establecer la dirección IP y subred) ha sido infructuosos lo que significa que la IP todavía se recibe de DHCP (con campos en gris) a pesar de que el valor por defecto puerta de enlace se ha establecido. ¿Cómo puedo solucionar esto?
El ReturnValue de EnableStatic es 70 (dirección IP no válida). Lo extraño es que los parámetros de entrada son los mismos que extraje de la NIC 2 segundos antes.
Aquí está el código (excepto GUI), http://pastebin.com/AE3dGhUz:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
namespace Static_NIC_Settings_Creator
{
public partial class Form1 : Form
{
private ManagementObjectCollection queryCollection;
private string[] networkInterfaces;
private int currentNIC;
private string[] ipAddress;
private string[] subnetMask;
private string[] defaultIPGateway;
private string[] dnsServerSearchOrder;
public Form1()
{
InitializeComponent();
getNICs();
}
private void convertButton_Click(object sender, EventArgs e)
{
if (networkInterfaces.Count() > 0)
{
//Get current NIC settings
if (!getNICSettings())
{
MessageBox.Show("Retrieving current NIC settings failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//Convert to static NIC settings
if (!setNICStatic())
{
MessageBox.Show("Setting NIC settings to static failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private void nicSelecter_SelectedIndexChanged(object sender, EventArgs e)
{
currentNIC = nicSelecter.SelectedIndex;
}
private void getNICs()
{
//Get NICS
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
queryCollection = query.Get();
//Make nic string array
int i = queryCollection.Count;
networkInterfaces = new string[i];
//Fill nic string array
i = 0;
foreach (ManagementObject mo in queryCollection)
{
networkInterfaces[i] = (String)mo["Description"];
i++;
}
//Fill dropbox with arraylist-data
nicSelecter.DataSource = networkInterfaces;
}
private Boolean getNICSettings()
{
//Get selected NIC
int i = 0;
foreach (ManagementObject mo in queryCollection)
{
//Get settings for specific NIC
if (i == currentNIC)
{
try
{
ipAddress = (String[])mo["IPAddress"];
subnetMask = (String[])mo["IPSubnet"];
defaultIPGateway = (String[])mo["DefaultIPGateway"];
dnsServerSearchOrder = (String[])mo["DNSServerSearchOrder"];
return true;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString(), "Critical: Unhandled error");
return false;
}
}
i++;
}
return false;
}
private Boolean setNICStatic()
{
//Get selected NIC
int i = 0;
foreach (ManagementObject mo in queryCollection)
{
//Get settings for specific NIC
if (i == currentNIC)
{
try
{
//Set static IP and subnet mask
ManagementBaseObject setIP;
ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = ipAddress;
newIP["SubnetMask"] = subnetMask;
setIP = mo.InvokeMethod("EnableStatic", newIP, null);
//Set default gateway
ManagementBaseObject setGateway;
ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = defaultIPGateway;
newGateway["GatewayCostMetric"] = new int[] { 1 };
setGateway = mo.InvokeMethod("SetGateways", newGateway, null);
//Set dns servers
ManagementBaseObject setDNS;
ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder");
newDNS["DNSServerSearchOrder"] = dnsServerSearchOrder;
setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
System.Windows.Forms.MessageBox.Show("Setting NIC settings returned: " + setDNS);
return true;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString(), "Critical: Unhandled error");
return false;
}
}
i++;
}
//No NICs
return false;
}
} //End class
}
¿Alguna idea?
Esto estaba retrasado. Había renunciado a esto hace mucho tiempo, pero ahora cuando estoy practicando en PS, también me tomé el tiempo para probar la aplicación C#. Parece haber algo sobre IP6, así que usé 'newIP [" IPAddress "] = new String [] {ipAddress [0]};' y similar para subred para obtener solo la configuración de ipv4. No es probable que se usen múltiples direcciones IP para su uso de todos modos. Great catch =) –
La descripción de la propiedad IPAddresses (https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx#properties) dice: "Esta propiedad puede contener IPv6 direcciones o direcciones IPv4 ". Ahora, cuando lo consultas, parece contener direcciones v4 y v6, pero tal vez solo cuente cuando tratas de cambiarlo (usando, por ejemplo, EnableStatic(). He notado el error 70 yo mismo, si usas direcciones mixtas con EnableStatic () –