如何以编程方式设置我的IP地址? [英] How to set my IP address programmatically?

查看:163
本文介绍了如何以编程方式设置我的IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I set my IP address programmatically?

我的应用程序正在检查它,使用 DelphiTricks (虽然我不知道如果代码来自 About.com 可能不会更好)

My application is checking it, using code from DelphiTricks (although I am not sure if the code from About.com might not be better)

我想通过编程方式设置地址用于测试目的。而且(我不知道这是否重要),即使我没有连接到任何网络(笔记本电脑上,在火车上),我也想要这样做。

I want to be able to set the address programmatically for testing purposes. And (I don't know if this is important), I want to be able to do so even I am not attached to any network (on a laptop, on a train).

推荐答案

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

To change the ip address of your network adapter you can use the EnableStatic method of the Win32_NetworkAdapterConfiguration WMI class or the AddIPAddress WinApi method.

尝试使用WMI的此示例。

Try this sample which uses the 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, 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.

这篇关于如何以编程方式设置我的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆