IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API, COM et SDKs Delphi Discussion :

Modifier adresse IP


Sujet :

API, COM et SDKs Delphi

  1. #1
    Membre éclairé Avatar de sondo
    Homme Profil pro
    Assistant aux utilisateurs
    Inscrit en
    Août 2004
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Burkina Faso

    Informations professionnelles :
    Activité : Assistant aux utilisateurs
    Secteur : Service public

    Informations forums :
    Inscription : Août 2004
    Messages : 540
    Par défaut Modifier adresse IP
    Bonjour,

    J'ai besoin d'aide pour faire un programme en delphi qui permet de modifier une adresse IP sans passer par le panneau de configuration.
    Je veux que l'utilisateur clique sur un bouton tout simplement, pour changer son adresse IP.
    Je veux le faire pour un ami qui possède un portable et qui se déplace d'une zone à l'autre pour travailler. Les adresses IP changent d'une zone à l'autre.
    Merci à Vous.

  2. #2
    tintin22
    Invité(e)
    Par défaut
    Salut,

    Voila le code que j'avais trouvé pour réaliser cela

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
     
    unit UConfigIP;
     
     
     
    interface
     
    function SetIpConfig(const AIpAddress : string;
                         const AGateWay : string = '';
                         const ASubnetMask : string = '') : integer;
     
     
    function SetDnsServers(const APrimaryDNS : string;
                           const AAlternateDNS : string = '') : integer;
     
     
    implementation
     
     
    uses ComObj, ActiveX, UrlMon,Variants,SysUtils;
     
    // ======================================================================
    // 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;
     
     
    // ====================================================
    // 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
    ------------------------------------------------ *)
     
    end.
    ... et voici l'appel aux fonctions :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
     
    uses UConfigIP;
     
    .....
     
    procedure TForm1.Button1Click(Sender: TObject);
    begin
         SetIpConfig('192.168.100.50','192.168.100.1','255.255.255.0');
         SetDnsServers('192.168.100.4','192.168.100.1');
    end;

  3. #3
    Rédacteur/Modérateur
    Avatar de ero-sennin
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2005
    Messages
    2 965
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2005
    Messages : 2 965
    Par défaut
    Salut,

    Tu peux aller voir ici

    C'est moins complet (on ne peut pas changer l'adresse DNS par exemple) mais c'est plus simple à mettre en oeuvre

    A+

  4. #4
    Membre éclairé Avatar de sondo
    Homme Profil pro
    Assistant aux utilisateurs
    Inscrit en
    Août 2004
    Messages
    540
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Burkina Faso

    Informations professionnelles :
    Activité : Assistant aux utilisateurs
    Secteur : Service public

    Informations forums :
    Inscription : Août 2004
    Messages : 540
    Par défaut
    Merci à vous deux.
    La solution sur ligne de commande est intéressante, mais je préfère celui programmée sous delphi, car c'est programme pour un profane.
    Encore merci.

  5. #5
    Membre confirmé Avatar de DarkChamallo
    Profil pro
    Inscrit en
    Mai 2002
    Messages
    113
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2002
    Messages : 113
    Par défaut
    J'avoue, c'est un deterrage de 5 ans, mais au cas où : ça ne marche plus sur Windows 7 - 64 bit Un message de mémoire insuffisante apparaît

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Modifier adresses IP dans un fichier PCAP en masse
    Par fargoth dans le forum Développement
    Réponses: 3
    Dernier message: 29/07/2009, 02h11
  2. obtenir et modifier adresse ip, dns..
    Par shawty dans le forum C++
    Réponses: 6
    Dernier message: 26/06/2006, 22h04
  3. Réponses: 2
    Dernier message: 26/05/2006, 19h18
  4. Réponses: 2
    Dernier message: 22/03/2006, 15h13
  5. modifier l'adresse d'un dll dans un .exe
    Par Mr Meuble dans le forum Windows
    Réponses: 4
    Dernier message: 02/03/2004, 16h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo