我在两个网络环境中使用我的笔记本电脑(在工作和家中),他们有不同的网络设置(IP地址,子网掩码,默认网关),因此每次回到家和我到达时都必须更改网络设置在办公室..无论如何要编写一个可以更改设置的代码,这样我只需要运行程序而不是手动更改设置?
我已经google了一下,发现this但我找不到我的网卡名称,似乎代码只更改了IP地址和子网掩码,但它不会更改默认网关。我是对的吗?
噢,顺便说一句,如果你们可以使用delphi编程来回答我的问题(特别是delphi 7),那就太好了。答案 0 :(得分:7)
正如您所指出的,此问题上发布的code不会更改默认网关,为此,您还必须执行SetGateways
方法。
尝试修改原始代码版本,允许您为网络适配器设置ip,mask和默认网关。
{$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, 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, 0], varVariant);
vGateWays[0]:= GateWay;
FOutParams:=FWbemObject.SetGateways(vGateWays);
// 0 - Successful completion, no reboot required
// 1 - 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.
注意..要获取网络设备名称,您可以使用网络连接列表