본문 바로가기

프로그램 경험/.Net

[C#] PC의 IP 변경하기


using System;
using System.Management;

namespace TcpIPWMI
{
	
	public class TcpIPWMI
	{

		public 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!");
				}
				catch(Exception ex)
				{
					Console.WriteLine("Unable to Set IP : " + ex.Message);
				}

			}
		}

		public 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["MACAddress"]) ;
				string[] ipaddresses = (string[]) objMO["IPAddress"];
				string[] subnets = (string[]) objMO["IPSubnet"];
				string[] gateways = (string[]) objMO["DefaultIPGateway"];

				Console.WriteLine(objMO["DefaultIPGateway"].ToString());

				Console.WriteLine("IPGateway");
				foreach(string sGate in gateways)
					Console.WriteLine (sGate);

				
				Console.WriteLine("Ipaddress");
				foreach(string sIP in ipaddresses)
					Console.WriteLine(sIP);
				
				Console.WriteLine("SubNet");
				foreach(string sNet in subnets)
					Console.WriteLine(sNet);

			}

		}

		public TcpIPWMI()
		{
			
		}


	}
}

출처 : http://www.codeproject.com/KB/system/cstcpipwmi.aspx