在 C# 中更改 IP 地址 [英] Changing IP address in C#

查看:54
本文介绍了在 C# 中更改 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要通过 UDP 连接连接到另一台计算机的 c# 程序.为了执行此操作,我需要临时更改计算机上网卡的 IP 地址,以便它们可以相互通信.我可以很好地做到这一点.但是,当我完成后,我想将我的 IP 地址恢复到以前的状态;即自动获取IP地址.

I have a c# program that needs to connect to another computer via a UDP connection. 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. I can do this just fine. However, when I'm done, I want to restore my IP address back to what it was before; which is to automatically obtain an IP address.

谁能告诉我如何将我的设置改回以前的设置?

Can someone tell me how to change my settings back to what they were previously?

谢谢,

菲尔

推荐答案

您可能需要查看此 SwitchNetConfig 项目.

You may want to check this SwitchNetConfig project.

您感兴趣的部分是如何更改IP:

The part that interest you is how to change the 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;
      }
    }
  }
}

这篇关于在 C# 中更改 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆