1
我有一个需要通过UDP连接连接到另一台计算机的c#程序。为了执行此操作,我需要临时更改我的计算机上网卡的IP地址,以便他们可以相互交谈。我可以做到这一点很好。但是,当我完成后,我想将我的IP地址恢复到之前的状态;即自动获取IP地址。在C#中更改IP地址
有人可以告诉我如何改变我的设置回到他们以前?
感谢,
菲尔
我有一个需要通过UDP连接连接到另一台计算机的c#程序。为了执行此操作,我需要临时更改我的计算机上网卡的IP地址,以便他们可以相互交谈。我可以做到这一点很好。但是,当我完成后,我想将我的IP地址恢复到之前的状态;即自动获取IP地址。在C#中更改IP地址
有人可以告诉我如何改变我的设置回到他们以前?
感谢,
菲尔
你可能要检查这个项目SwitchNetConfig。
,你是关心如何更改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;
}
}
}
}
这不适用于Win 7,似乎 – Kaitlyn
你能解释一下为什么你在第一时间更改地址?无论我想象的IP地址如何,UDP都应该可用。 –
你意识到当你这样做时,任何正在运行的其他应用程序都会使连接断开?如果最终用户在运行应用程序的同时在另一个应用程序中进行处理,则这可能会很危险。 – tsells