简体   繁体   English

在C#中更改IP地址

[英]Changing IP address in C#

I have ac# program that needs to connect to another computer via a UDP connection. 我有一个ac#程序,需要通过UDP连接连接到另一台计算机。 In order to perform this operation, I need to temporarily change the IP address of my network card on my computer, so they can talk to one another. 为了执行此操作,我需要临时更改计算机上网卡的IP地址,以便它们可以相互通信。 I can do this just fine. 我可以做的很好。 However, when I'm done, I want to restore my IP address back to what it was before; 但是,完成后,我想将我的IP地址恢复到以前的状态。 which is to automatically obtain an IP address. 自动获取IP地址。

Can someone tell me how to change my settings back to what they were previously? 有人可以告诉我如何将设置更改回以前的设置吗?

Thanks, 谢谢,

Phil 菲尔

You may want to check this SwitchNetConfig project. 您可能要检查此SwitchNetConfig项目。

The part that interest you is how to change the IP: 您感兴趣的部分是如何更改IP:

public static void SetIP( string nicName, string IpAddresses, 
  string SubnetMask, string Gateway, string DnsSearchOrder)
{
  ManagementClass mc = new ManagementClass(
    "Win32_NetworkAdapterConfiguration");
  ManagementObjectCollection moc = mc.GetInstances();

  foreach(ManagementObject mo in moc)
  {
    // Make sure this is a IP enabled device. 

    // Not something like memory card or VM Ware

    if( mo["IPEnabled"] as bool )
    {
      if( mo["Caption"].Equals( nicName ) )
      {

        ManagementBaseObject newIP = 
          mo.GetMethodParameters( "EnableStatic" );
        ManagementBaseObject newGate = 
          mo.GetMethodParameters( "SetGateways" );
        ManagementBaseObject newDNS = 
          mo.GetMethodParameters( "SetDNSServerSearchOrder" );

        newGate[ "DefaultIPGateway" ] = new string[] { Gateway };
        newGate[ "GatewayCostMetric" ] = new int[] { 1 };

        newIP[ "IPAddress" ] = IpAddresses.Split( ',' );
        newIP[ "SubnetMask" ] = new string[] { SubnetMask };

        newDNS[ "DNSServerSearchOrder" ] = DnsSearchOrder.Split(',');

        ManagementBaseObject setIP = mo.InvokeMethod( 
          "EnableStatic", newIP, null);
        ManagementBaseObject setGateways = mo.InvokeMethod( 
          "SetGateways", newGate, null);
        ManagementBaseObject setDNS = mo.InvokeMethod( 
          "SetDNSServerSearchOrder", newDNS, null);

        break;
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM