C#
[C#] IP 변경
by Jcoder
2021. 7. 25.
public bool IPChangeRun(string ip, string subnet, string gateWay)
{
string myDesc = System.Configuration.ConfigurationManager.AppSettings["NICName"]; // NIC 정보
string address = ip; // 아이피 정보
string subnetMask = subnet; // 서브넷 정보
string gateway = gateWay; //게이트웨이 정보
using (System.Management.ManagementClass adapterConfig = new System.Management.ManagementClass("Win32_NetworkAdapterConfiguration"))
{
using (System.Management.ManagementObjectCollection networkCollection = adapterConfig.GetInstances())
{
foreach (System.Management.ManagementObject adapter in networkCollection)
{
string description = adapter["Description"] as string;
if (string.Compare(description, myDesc, StringComparison.InvariantCultureIgnoreCase) == 0)
{
try
{
System.Management.ManagementBaseObject newGateway = adapter.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
System.Management.ManagementBaseObject newAddress = adapter.GetMethodParameters("EnableStatic");
newAddress["IPAddress"] = new string[] { address };
newAddress["SubnetMask"] = new string[] { subnetMask };
adapter.InvokeMethod("EnableStatic", newAddress, null);
adapter.InvokeMethod("SetGateways", newGateway, null);
return true;
}
catch
{
return false;
}
}
}
}
}
return true;
}