Function Test-IPv4Address($ipAddress) {
if($testAddress -match "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b") {
$addressValid = $true
} else {
$addressValid = $false
}
return $addressValid
}
#--------------------------------------------------------------------------------------------------#
Set-Variable -name testAddresses -option Constant -value @("192.168.1.1","546.23.10.12","8.8.8.8","127.0.999.26")
#--------------------------------------------------------------------------------------------------#
foreach($testAddress in $testAddresses) {
if((Test-IPv4Address $testAddress)) {
Write-Host "$testAddress is a validly formatted IPv4 Address" -foregroundColor Green
} else {
Write-Host "$testAddress is not a validly formatted IPv4 Address" -foregroundColor Red
}
}
Showing posts with label Networking. Show all posts
Showing posts with label Networking. Show all posts
Tuesday, June 14, 2011
Validate IPv4 Addresses in PowerShell
Here is a simple function to validate if a IPv4 address meets the RFC. It does not confirm if the host associated to the IP Address is accessible. To do that with PowerShell, you need to utilize the System.Net.NetworkInformation.Ping class. The validation is performed by a fairly complex Regular Expression using '-match'.
Labels:
Networking,
PowerShell
Friday, February 25, 2011
IP Address to Binary
When I was teaching myself subnetting some time ago, I wrote a perl script to assist in learning the conversion. There are many ways to do this but I wanted a method to help me learn to do the conversion in my head. This is why the subroutine is written out as collection of if than statements to represent the bits in the octet.
#!/usr/bin/perl
# use: ./ip2binary.pl 192.168.1.1
use strict;
my $ip = $ARGV[0];
if($ip =~ /\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/) {
my @binary;
my @octets = split(/\./,$ip);
foreach my $octet (@octets) {
push (@binary, return_binary($octet));
}
print join(".",@binary) . "\n";
} else {
print "$ip is not a valid IP\n";
}
exit;
sub return_binary {
my $decimal = $_[0];
my @binary;
if($decimal >= 128) {
$binary[0] = 1;
$decimal -= 128;
} else {
$binary[0] = 0;
}
if($decimal >= 64) {
$binary[1] = 1;
$decimal -= 64;
} else {
$binary[1] = 0;
}
if($decimal >= 32) {
$binary[2] = 1;
$decimal -= 32;
} else {
$binary[2] = 0;
}
if($decimal >= 16) {
$binary[3] = 1;
$decimal -= 16;
} else {
$binary[3] = 0;
}
if($decimal >= 8) {
$binary[4] = 1;
$decimal -= 8;
} else {
$binary[4] = 0;
}
if($decimal >= 4) {
$binary[5] = 1;
$decimal -= 4;
} else {
$binary[5] = 0;
}
if($decimal >= 2) {
$binary[6] = 1;
$decimal -= 2;
} else {
$binary[6] = 0;
}
if($decimal >= 1) {
$binary[7] = 1;
$decimal -= 1;
} else {
$binary[7] = 0;
}
return join("",@binary);
}
Labels:
Networking,
Perl
Subscribe to:
Posts (Atom)