我在两个网络环境中使用我的笔记本电脑(在工作和家中),他们有不同的网络设置(IP地址,子网掩码,默认网关),所以我每次回到家,当我到达办公室时都要更改网络设置..无论如何编写一个可以更改设置的代码,以便我只需要运行程序而不是手动更改设置?
我google了一下,发现了this,但我找不到我的网卡名称,似乎代码只更改了IP地址和子网掩码,但它没有改变默认网关..我是否正确?
哦顺便问一下,如果你们可以使用delphi编程来回答我的问题(特别是delphi 7)会很棒
解决方法
正如您所指出的,在此问题上发布的
code不会更改默认网关,为此,您还必须执行
SetGateways
方法.
尝试使用此原始代码的修改版本,它允许您为网络适配器设置ip,掩码和默认网关.
{$APPTYPE CONSOLE} {$R *.res} uses SysUtils,ActiveX,Variants,ComObj; procedure SetStaticIpAddress(const NetworkCard,IPAddress,Mask,GateWay :string); const WbemUser =''; WbemPassword=''; WbemComputer='localhost'; wbemFlagForwardOnly = $00000020; var FSWbemLocator : OLEVariant; FWMIService : OLEVariant; FWbemObjectSet : OLEVariant; FWbemObject : OLEVariant; FOutParams : OLEVariant; vIpAddress : OLEVariant; vGateWays : OLEVariant; vMask : OLEVariant; oEnum : IEnumvariant; iValue : LongWord; begin FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); FWMIService := FSWbemLocator.ConnectServer(WbemComputer,'root\CIMV2',WbemUser,WbemPassword); FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM Win32_NetworkAdapterConfiguration Where Description="%s"',[NetworkCard]),'WQL',wbemFlagForwardOnly); oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant; if oEnum.Next(1,FWbemObject,iValue) = 0 then begin vIpAddress := VarArrayCreate([0,0],varVariant); vIpAddress[0]:= IPAddress; vMask := VarArrayCreate([0,varVariant); vMask[0]:= Mask; FOutParams:=FWbemObject.EnableStatic(vIpAddress,vMask); // 0 - Successful completion,no reboot required // 1 - Successful completion,reboot required Writeln(Format('EnableStatic ReturnValue %s',[FOutParams])); vGateWays := VarArrayCreate([0,varVariant); vGateWays[0]:= GateWay; FOutParams:=FWbemObject.SetGateways(vGateWays); // 0 - Successful completion,reboot required Writeln(Format('SetGateways ReturnValue %s',[FOutParams])); end else Writeln('Network card not found'); end; begin try CoInitialize(nil); try SetStaticIpAddress('network device','192.168.1.1','255.255.255.0','192.168.1.2'); finally CoUninitialize; end; except on E:EOleException do Writeln(Format('EOleException %s %x',[E.Message,E.ErrorCode])); on E:Exception do Writeln(E.Classname,':',E.Message); end; Writeln('Press Enter to exit'); Readln; end.