Set static IP (Perl)

This code can be found in Chapter 1 of Windows Server 2003 Networking Recipes

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# From the book "Windows Server 2003 Networking Recipes"

# This code sets the local IP address
#   to a static IP of 10.0.0.100,
#   with a subnet mask of 255.0.0.0,
#   a default gateway of 10.0.0.1,
#   and a metric of 1
# ------ SCRIPT CONFIGURATION ------

use Win32::OLE qw(in);

$strComputer = '.';
$strIPAddress = ['10.0.0.100'];
$strSubnetMask = ['255.0.0.0'];
$strGateway = ['10.0.0.1'];
$strGatewayMetric = [1];
# --------- END CONFIGURATION ------

$objWMIService = Win32::OLE->GetObject('winmgmts:' . '{impersonationLevel=impersonate}!\\\\' . $strComputer . '\\root\\cimv2');

$adapters = $objWMIService->ExecQuery('Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE');

foreach my $a (in $adapters) {
    $errIP = $a->EnableStatic($strIPAddress, $strSubnetMask);
    $errGateways = $a->SetGateways($strGateway, $strGatewayMetric);
    if ($errIP == 0) {
        print "Success! The IP address has been changed.\n";
    }
    else {
        print "Error! The IP address could not be changed.\n";
    }
}

This code has been viewed 1269 times.

New from the creators of TechTasks.com: StatSheet.com