[C#] IP 주소 확인하기

#반드시 관리자 권한으로 실행해야만 한다.

private void button1_Click(object sender, EventArgs e) {

    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection objMOC = objMC.GetInstances();
    foreach (ManagementObject mo in objMOC) {
        if (!(bool)mo["IPEnabled"]) {
            continue;
        }

        try {
            ManagementBaseObject objNewIP = null;
            ManagementBaseObject objSetIP = null;
            ManagementBaseObject objNewGate = null;
            ManagementBaseObject objdns = null;

            objNewIP = mo.GetMethodParameters("EnableStatic");
            objNewGate = mo.GetMethodParameters("SetGateways");
            objdns = mo.GetMethodParameters("SetDNSServerSearchOrder");

            //Set Gateway
            objNewGate["DefaultIPGateway"] = new string[] { "172.30.1.254" };
            objNewGate["GatewayCostMetric"] = new int[] { 1 };

            //Set IP
            objNewIP["IPAddress"] = new string[] { "172.30.1.99" };

            //Set Subnet
            objNewIP["SubnetMask"] = new string[] { "255.255.255.0" };
            objSetIP = mo.InvokeMethod("EnableStatic", objNewIP, null);
            objSetIP = mo.InvokeMethod("SetGateways", objNewGate, null);

            //DNS 
            objdns["DNSServerSearchOrder"] = new string[] { "168.126.63.1", "168.126.63.2" };
            mo.InvokeMethod("SetDNSServerSearchOrder", objdns, null);

            MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!");
        } catch (Exception ex) {
            MessageBox.Show("Unable to Set IP : " + ex.Message);
        }
    }
}

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다