1

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?

Thanks,

Phil

Phil Price
  • 11
  • 1
  • 2
  • 1
    Can you explain why you have to change the address in the first place? UDP should be usable regardless of the IP address I would have thought. – Steve Townsend Sep 21 '11 at 14:09
  • 1
    You realize that when you do this any other application that is running will have it's connection broken? This could be dangerous for end users if they are doing processing in another application at the same time they are running your application. – tsells Sep 21 '11 at 14:25

1 Answers1

5

You may want to check this SwitchNetConfig project.

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;
      }
    }
  }
}
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
  • Just a side note: the "if (mo["IPEnabled"] as bool) invokes error since "as" is not valid with non-nullable types. Use "if (Convert.ToBoolean(mo["IPEnabled"]) == true)" instead :) – That Marc May 27 '20 at 19:44