IP地址,网关,dns已经根据MAC地址分配好,如何在delphi中设置或修改某一个电脑系统里的原有IP设置呢,有没有相关的API可以调用.谢谢!

解决方案 »

  1.   

    这里有一个例子:讓GHOST後的電腦自動修正電腦名與IP位址 
    http://www.cnblogs.com/zhenyulu/archive/2004/09/03/39156.aspx
    一、問題提出
    當上實驗中心主任後的一個棘手的問題就是機房管理。機房不大,只有60多台電腦,而且已經裝上了海光硬碟保護卡豪華版,可以直接網路GHOST硬碟。只要安裝好一台電腦,就可以在6個小時左右將40G硬碟資訊傳遍每一台電腦。雖然是一個小小的實驗中心,也要大家上機服務,什等級考試、財務會計、外貿類比、軟體發展樣樣具全。這樣,在40G硬碟中裝了6個作業系統(DOS、Win 98、Win 2003 Server、Win 2000 Server、WinXP、Win 2000 Server(英文版MCSE用))。在與補丁和病毒做了一番鬥爭後,剩下的問題就是自動更新IP地址與電腦名。機房中的每台機器都有一個編號,機器的IP分配也與編號相關。海光藍卡雖然提供自動修改IP的功能,但對Server版的作業系統不起作用(修改完後,系統就癱瘓了),對非Server版的作業系統雖然起作用,但IP位址分配是隨機的,如果想人定制,必須自己建立MAC地址與IP地址的映射表。總之,使用起來非常不方便,何況還沒法對NT Server修改IP呢。打電話諮詢海光公司,回話是:你用的保護卡不具備修改NT Server IP地址的功能,我們這裏的最新品是MAX版,可以解決你的問題。這不是又要從兜裏掏銀子嗎!還是自己動手解決吧。
    二、解決辦法
    一開始,我使用DHCP動態分配IP,對每台機器保留一固定IP地址,但由於所有的機器都是克隆出來的,機器名完全一樣,每次機都報有重名電腦存在,還影響了網上鄰居的使用。最後一生氣,乾脆自己編一個自動修改機器名與IP地址的程式。考查了一下,可以使用Windows Script或是WinBatch實現,不過需要在機器上安裝這些軟體,似乎有些大材小用。最後決定使用Delphi自己編寫一個自動修改IP的程式。這樣,借助海光藍卡上自動修改IP的功能(說是自動修改IP,經我研究,實際上就是解開硬碟保護,自動將每個系統重新動一下,在動的過程中,海光自己的驅動程式完成修改工作。),實現自己修改IP。具體方法就是,不再安裝海光自動修改IP的程式,改成自己的程式,讓系統在第一次動的時候自動修正IP和電腦名,並重新動機器。說幹就幹,首先將所有機器號與MAC映射表存儲成Access資料庫,並將IP位址設置自動獲取DHCP,防止機時衝突。然後在Delphi中編寫如下程式:
    unit UpdateIP;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, NB30, StdCtrls, DB, ADODB;type
      TfrmUpdateIPAddress = class(TForm)
        adoCntAccess: TADOConnection;
        adoDSMacAddress: TADODataSet;
        procedure adoCntAccessBeforeConnect(Sender: TObject);
        procedure FormShow(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;var
      frmUpdateIPAddress: TfrmUpdateIPAddress;implementation{$R *.dfm}//============================================================
    // 設置資料庫路徑
    //============================================================
    procedure TfrmUpdateIPAddress.adoCntAccessBeforeConnect(Sender: TObject);
    begin
      adoCntAccess.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Password="";' +
        'User ID=Admin;Data Source=' + ExtractFilePath(Application.ExeName) +
        '\MacData.mdb;Mode=Share Deny None;Extended Properties=""';
    end;//============================================================
    // 獲取電腦的 MAC 位址
    //============================================================
    function NBGetAdapterAddress(a :Integer) : string;
    var 
      NC : TNCB;
      ADAPTE : TADAPTERSTATUS;
      LANAENU : TLANAENUM;
      intId : Integer;
      cR : Char;
      strTem : string;
    begin 
      Result := ''; 
      try 
        ZeroMemory(@NC, SizeOf(NC)); 
        NC.ncb_command := Chr(NCBENUM); 
        cR := NetBios(@NC);
     
        //Reissue enum command 
        NC.ncb_buffer := @LANAENU; 
        NC.ncb_length := SizeOf(LANAENU); 
        cR := NetBios(@NC); 
        if Ord(cR) <> 0 then
          exit; 
     
        ZeroMemory(@NC, SizeOf(NC));
        NC.ncb_command := Chr(NCBRESET); 
        NC.ncb_lana_num := LANAENU.lana[a]; 
        cR := NetBios(@NC); 
        if Ord(cR) <> 0 then 
          exit; 
     
        ZeroMemory(@NC, SizeOf(NC)); 
        NC.ncb_command := Chr(NCBASTAT); 
        NC.ncb_lana_num := LANAENU.lana[a]; 
        StrPCopy(NC.ncb_callname, '*'); 
        NC.ncb_buffer := @ADAPTE; 
        NC.ncb_length := SizeOf(ADAPTE); 
        cR := NetBios(@NC);
        strTem := '';
        for intId := 0 To 5 do
          strTem := strTem+ InttoHex(Integer(ADAPTE.adapter_address[intId]), 2);
        Result := strTem;
      finally
      end;
    end;//============================================================
    // 設置電腦名
    //============================================================
    function SetComputerName(AComputerName: string): Boolean;
    var
      ComputerName: array[0..MAX_COMPUTERNAME_LENGTH + 1] of Char;
    begin
      StrPCopy(ComputerName, AComputerName);
      Result := Windows.SetComputerName(ComputerName);
    end;//============================================================
    // &#61181;動時自動修改IP位址以及電腦名
    //============================================================
    procedure TfrmUpdateIPAddress.FormShow(Sender: TObject);
    var
      sMac, sNum, sComputerName, BatchFileName:  string;
      ProcessInfo:  TProcessInformation;
      StartUpInfo:  TStartupInfo;
    begin
      sMac := NBGetAdapterAddress(0);  AdoCntAccess.Connected := True;
      adoDSMacAddress.Close;
      adoDSMacAddress.Parameters.ParamByName('mac').Value := sMac;
      adoDSMacAddress.Open;  if adoDSMacAddress.RecordCount = 0 then
        Application.Terminate;  sNum := Trim(adoDSMacAddress.FieldByName('ComputerID').Value);  //設置電腦名
      sComputerName := 'Stu_' + sNum;
      if not SetComputerName(sComputerName) then
      begin
        ShowMessage('電腦名沒有設置成功!');
        Application.Terminate;
      end;  //設置IP地址、DNS等
      BatchFileName  :=  ExtractFilePath(ParamStr(0))  +  'AutoUpdate.bat ' + sNum;
      StartUpInfo.dwFlags  :=  STARTF_USESHOWWINDOW;
      StartUpInfo.wShowWindow  :=  SW_Hide;
      if CreateProcess(nil, PChar(BatchFileName),  nil,  nil,
        False, IDLE_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo) then
      begin
        CloseHandle(ProcessInfo.hThread);
        CloseHandle(ProcessInfo.hProcess);
      end;
      Application.Terminate;
    end;end.
      

  2.   

    有没有现成的系统API啊?上面这个实现起来还是比较麻烦
      

  3.   

    我自己找到了,答案如下:
    Question/Problem/Abstract:In article #4388 Radikal Q3 demonstrates how to set the IP Address,Subnet and Gateway of a network card by EXECUTING NETSH.EXE with parameters. This example shows how to do it via the WMI API OLE Classes. If IP ADDRESS is NULLSTR or 'DHCP' then the IP Address is set by DHCP else a STATIC IP Address is set. Parameters are .. AIpAddress - If Null String or 'DHCP' then DHCP is ENABLED     else STATIC IP is set. AGateWay   - [Optional] If Omitted then GATEWAY is left unchanged. SubnetMask - [Optional] If Omited then default = '255.255.255.0'. Examples if SetIpConfig('196.11.175.221') = 0 then ... // Set STATIC IP 
    if SetIpConfig('') = 0 then ..    // Set to DHCP 
    if SetupConfig('dhcp') = 0 then ... // Same as above 
    if SetIpConfig('196.11.175.221','196.11.175.1') = 0 then ..  // STATIC + GATEWAY **** THERE IS HOWEVER ONE PROBLEM I HAVE ****** 
    **** AND HOPE SOMEONE OUT THERE CAN HELP ****** When setting the adapter to DHCP ALL Mapped drives and printers work correctly as expected. When setting the adapter to STATIC IP, the IP changes successfully but any mapped devices (drives,printers etc.) won't work. Trying to access a mapped drives gives error saying the "local device is already in use'. I don't know if you have to call some sort of network mapping refresh call or something to notify that a static IP address has changed ? Anyone out there have any ideas ? Also shown is SetDnsServers() whereby the DNS Primary and Alternate Servsers may be specified. If the function is called with Null String for APrimaryDNS then the DNS list is cleared. There are many things you can do once you get the oNetAdapter Object. See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/wmi_tasks__networking.asp for the help on the SDK. 
    Answer:
    uses ComObj, ActiveX, UrlMon; // ====================================================================== 
    // SetIpConfig() 
    // Set IPAddress, Gateway and Subnetmask via WMI 
    // Arguments ... 
    // AIpAddress - If Null String or 'DHCP' then DHCP is ENABLED 
    //              else STATIC IP is set. 
    // AGateWay   - [Optional] If Omitted then GATEWAY is left unchanged. 
    // SubnetMask - [Optional] If Omited then default = '255.255.255.0'. 
    // 
    // SetDnsServers() 
    // Set  DNS Servers via WMI 
    // Arguments ... 
    // APrimaryDNS   - If Null String then DNS Server List is CLEARED. 
    // AAlternateDNS - [Optional] 
    // 
    // Return Values ... 
    //   0 Successful completion, no reboot required. 
    //   1 Successful completion, reboot required. 
    //  -1 Unknown OLE Error 
    //  64 Method not supported on this platform. 
    //  65 Unknown failure. 
    //  66 Invalid subnet mask. 
    //  67 An error occurred while processing an instance that was returned. 
    //  68 Invalid input parameter. 
    //  69 More than five gateways specified. 
    //  70 Invalid IP address. 
    //  71 Invalid gateway IP address. 
    //  72 An error occurred while accessing the registry for the info. 
    //  73 Invalid domain name. 
    //  74 Invalid host name. 
    //  75 No primary or secondary WINS server defined. 
    //  76 Invalid file. 
    //  77 Invalid system path. 
    //  78 File copy failed. 
    //  79 Invalid security parameter. 
    //  80 Unable to configure TCP/IP service. 
    //  81 Unable to configure DHCP service. 
    //  82 Unable to renew DHCP lease. 
    //  83 Unable to release DHCP lease. 
    //  84 IP not enabled on adapter. 
    //  85 IPX not enabled on adapter. 
    //  86 Frame/network number bounds error. 
    //  87 Invalid frame type. 
    //  88 Invalid network number. 
    //  89 Duplicate network number. 
    //  90 Parameter out of bounds. 
    //  91 Access denied. 
    //  92 Out of memory. 
    //  93 Already exists. 
    //  94 Path, file, or object not found. 
    //  95 Unable to notify service. 
    //  96 Unable to notify DNS service. 
    //  97 Interface not configurable. 
    //  98 Not all DHCP leases could be released or renewed. 
    //  100 DHCP not enabled on adapter. 
    // ====================================================================== 
    // ================================================================== 
    // IP Address,Gateway and Subnet Mask 
    // EnableStatic takes array of string as a parameter 
    // for the Addresses. You may wish to rewrite this using 
    // array of string as parameter for multiple IP Addresses. 
    // I only have use for 1 IP address and Gateway in our application 
    // but it's nice to be able to expand it for other users. 
    // ================================================================== function SetIpConfig(const AIpAddress : string; 
                         const AGateWay : string = ''; 
                         const ASubnetMask : string = '') : integer; 
    var Retvar : integer; 
        oBindObj : IDispatch; 
        oNetAdapters,oNetAdapter, 
        oIpAddress,oGateWay, 
        oWMIService,oSubnetMask : OleVariant; 
        i,iValue : longword; 
        oEnum : IEnumvariant; 
        oCtx : IBindCtx; 
        oMk : IMoniker; 
        sFileObj : widestring; 
    begin 
      Retvar := 0; 
      sFileObj := 'winmgmts:\\.\root\cimv2';   // Create OLE [IN} Parameters 
      oIpAddress := VarArrayCreate([1,1],varOleStr); 
      oIpAddress[1] := AIpAddress; 
      oGateWay := VarArrayCreate([1,1],varOleStr); 
      oGateWay[1] := AGateWay; 
      oSubnetMask := VarArrayCreate([1,1],varOleStr); 
      if ASubnetMask = '' then 
        oSubnetMask[1] := '255.255.255.0' 
      else 
        oSubnetMask[1] := ASubnetMask;   // Connect to WMI - Emulate API GetObject() 
      OleCheck(CreateBindCtx(0,oCtx)); 
      OleCheck(MkParseDisplayNameEx(oCtx,PWideChar(sFileObj),i,oMk)); 
      OleCheck(oMk.BindToObject(oCtx,nil,IUnknown,oBindObj)); 
      oWMIService := oBindObj;   oNetAdapters := oWMIService.ExecQuery('Select * from ' + 
                                            'Win32_NetworkAdapterConfiguration ' + 
                                            'where IPEnabled=TRUE'); 
      oEnum := IUnknown(oNetAdapters._NewEnum) as IEnumVariant;   while oEnum.Next(1,oNetAdapter,iValue) = 0 do begin 
        try 
          // Set by DHCP ? (Gateway and Subnet ignored) 
          if (AIpAddress = '') or SameText(AIpAddress,'DHCP') then 
            Retvar := oNetAdapter.EnableDHCP 
          // Set via STATIC ? 
          else begin 
            Retvar := oNetAdapter.EnableStatic(oIpAddress,oSubnetMask); 
            // Change Gateway ? 
            if (Retvar = 0) and (AGateWay <> '') then 
              Retvar := oNetAdapter.SetGateways(oGateway);         // *** This is where we need some sort of *** 
            // *** Network Mapped Resource Refresh    *** 
          end; 
        except 
          Retvar := -1; 
        end;     oNetAdapter := Unassigned; 
      end;   oGateWay := Unassigned; 
      oSubnetMask := Unassigned; 
      oIpAddress := Unassigned; 
      oNetAdapters := Unassigned; 
      oWMIService := Unassigned; 
      Result := Retvar; 
    end; 
      

  4.   

    // ==================================================== 
    // Set DNS Servers 
    // Instead of Primary and Alternate you may wish 
    // to rewrite this using array of string as the 
    // parameters as SetDNSServerSearchOrder will take 
    // a list of many DNS addresses. I only have use for 
    // Primary and Alternate. 
    // ==================================================== function SetDnsServers(const APrimaryDNS : string; 
                           const AAlternateDNS : string = '') : integer; 
    var Retvar : integer; 
        oBindObj : IDispatch; 
        oNetAdapters,oNetAdapter, 
        oDnsAddr,oWMIService : OleVariant; 
        i,iValue,iSize : longword; 
        oEnum : IEnumvariant; 
        oCtx : IBindCtx; 
        oMk : IMoniker; 
        sFileObj : widestring; 
    begin 
      Retvar := 0; 
      sFileObj := 'winmgmts:\\.\root\cimv2'; 
      iSize := 0; 
      if APrimaryDNS <> '' then inc(iSize); 
      if AAlternateDNS <> '' then inc(iSize);   // Create OLE [IN} Parameters 
      if iSize > 0 then begin 
       oDnsAddr := VarArrayCreate([1,iSize],varOleStr); 
       oDnsAddr[1] := APrimaryDNS; 
       if iSize > 1 then oDnsAddr[2] := AAlternateDNS; 
      end;   // Connect to WMI - Emulate API GetObject() 
      OleCheck(CreateBindCtx(0,oCtx)); 
      OleCheck(MkParseDisplayNameEx(oCtx,PWideChar(sFileObj),i,oMk)); 
      OleCheck(oMk.BindToObject(oCtx,nil,IUnknown,oBindObj)); 
      oWMIService := oBindObj;   oNetAdapters := oWMIService.ExecQuery('Select * from ' + 
                                            'Win32_NetworkAdapterConfiguration ' + 
                                            'where IPEnabled=TRUE'); 
      oEnum := IUnknown(oNetAdapters._NewEnum) as IEnumVariant;   while oEnum.Next(1,oNetAdapter,iValue) = 0 do begin 
        try 
          if iSize > 0 then 
            Retvar := oNetAdapter.SetDNSServerSearchOrder(oDnsAddr) 
          else 
            Retvar := oNetAdapter.SetDNSServerSearchOrder(); 
        except 
          Retvar := -1; 
        end;     oNetAdapter := Unassigned; 
      end;   oDnsAddr := Unassigned; 
      oNetAdapters := Unassigned; 
      oWMIService := Unassigned; 
      Result := Retvar; 
    end; (* ---------------------------------------------------- 
    See the Miscrosoft MSDN Documentation for the 
    Win32_NetworkAdapterConfiguration Class 
    (implemented as oNetAdatper in my examples), 
    There are many more calls besides EnableStatic, 
    EnableDHCP and SetDNBSServerSearchOrder. Some of them are ... DisableIPSec 
    EnableDHCP 
    EnableDNS 
    EnableIPFilterSec 
    EnableIPSec 
    EnableStatic 
    EnableWINS 
    ReleaseDHCPLease 
    ReleaseDHCPLeaseAll 
    RenewDHCPLease 
    RenewDHCPLeaseAll 
    SetArpAlwaysSourceRoute 
    SetArpUseEtherSNAP 
    SetDatabasePath 
    SetDeadGWDetect 
    SetDefaultTTL 
    SetDNSDomain 
    SetDNSServerSearchOrder 
    SetDNSSuffixSearchOrder 
    SetDynamicDNSRegistration 
    SetForwardBufferMemory Specifies 
    SetGateways 
    SetIGMPLevel 
    SetIPConnectionMetric 
    SetIPUseZeroBroadcast 
    SetIPXFrameTypeNetworkPairs 
    SetIPXVirtualNetworkNumber 
    SetKeepAliveInterval 
    SetKeepAliveTime 
    SetNumForwardPackets 
    SetPMTUBHDetect 
    SetPMTUDiscovery 
    SetTcpipNetbios 
    SetTcpMaxConnectRetransmissions 
    SetTcpMaxDataRetransmissions 
    SetTcpNumConnections 
    SetTcpUseRFC1122UrgentPointer 
    SetTcpWindowSize 
    SetWINSServer 
    ------------------------------------------------ *) 网址:http://www.delphi3000.com/articles/article_4392.asp?SK=