delphi – 如何以编程方式设置我的IP地址?

前端之家收集整理的这篇文章主要介绍了delphi – 如何以编程方式设置我的IP地址?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何以编程方式设置我的IP地址?

我的应用程序正在检查它,使用DelphiTricks中的代码(虽然我不确定About.com代码是否可能更好)

我希望能够以编程方式设置地址以进行测试.并且(我不知道这是否重要),我希望能够这样做,即使我没有连接到任何网络(在笔记本电脑上,在火车上).

解决方法

要更改网络适配器的IP地址,可以使用 Win32_NetworkAdapterConfiguration WMI类的 EnableStatic方法AddIPAddress WinApi方法.

试试这个使用WMI的示例.

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils,ActiveX,Variants,ComObj;

procedure  SetStaticIpAddress(const NetworkCard,IPAddress,Mask :string);
const
  WbemUser    ='';
  WbemPassword='';
  WbemComputer='localhost';
  wbemFlagForwardOnly = $00000020;
var
  FSWbemLocator   : OLEVariant;
  FWMIService     : OLEVariant;
  FWbemObjectSet  : OLEVariant;
  FWbemObject     : OLEVariant;
  FOutParams      : OLEVariant;
  vIpAddress      : 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('ReturnValue  %s',[FOutParams]));
  end
  else
  Writeln('Network card not found');
end;


begin
 try
    CoInitialize(nil);
    try
      SetStaticIpAddress('Network card name','192.168.1.1','255.255.255.0');
    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.
原文链接:https://www.f2er.com/delphi/101186.html

猜你在找的Delphi相关文章