برای اینکار دوتابع نیاز دارید. تابع اول مشخصات فعلی شبکه را می دهد و تابع دوم آی پی مورد نظر شما را فعال می کند.
کد:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace ConfigurationIP
{
class Program
{
static void Main(string[] args)
{
ListIP();
SetIP("192.168.22.77", "255.255.255.0", "192.168.22.22");
}
public static void ListIP()
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration ");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["ipEnabled"])
continue;
Console.WriteLine(objMO["Caption"] + "," +
objMO["ServiceName"] + "," + objMO["IPAddress"]);
string[] ipAddresses = (string[])objMO["IPAddress"];
string[] Subnets = (string[])objMO["IPSubnet"];
string[] Gateways = (string[])objMO["DefaultIPGateway"];
Console.WriteLine("Printing Default Gateway Info:");
Console.WriteLine(objMO["DefaultIPGateway"]);
Console.WriteLine("Printing IPGateway info:");
foreach (string sGate in Gateways)
{
Console.WriteLine(sGate);
}
Console.WriteLine("Printing IPAddress info:");
foreach (string sIP in ipAddresses)
{
Console.WriteLine(sIP);
}
Console.WriteLine("Printing SubNet Info:");
foreach (string sNet in Subnets)
{
Console.WriteLine(sNet);
}
}
Console.ReadLine();
}
public static void SetIP(string IPAddress, string SubnetMask, string Gateway)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration ");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
objNewGate["DefaultIPGateway"] = new string[]
{
Gateway
};
objNewGate["GatewayCostMetric"] = new int[]
{
1
};
objNewIP["IPAddress"] = new string[]
{
IPAddress
};
objNewIP["SubnetMask"] = new string[]
{
SubnetMask
};
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
Console.WriteLine("Updated IPAddress, SubnetMask and Default Gateway!");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Unable to Set IP : " + ex.Message);
Console.ReadLine();
}
}
}
}
}