Parse an IP Address: Difference between revisions

Content added Content deleted
No edit summary
Line 1,712: Line 1,712:
::1 00000000000000000000000000000001 1 IPv6
::1 00000000000000000000000000000001 1 IPv6
[::1]:80 00000000000000000000000000000001 1 IPv6 80</pre>
[::1]:80 00000000000000000000000000000001 1 IPv6 80</pre>

=={{header|PowerShell}}==
<lang PowerShell>
function Get-IpAddress
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$InputObject
)

Begin
{
function Get-Address ([string]$Address)
{
if ($Address.IndexOf(".") -ne -1)
{
$Address, $port = $Address.Split(":")

[PSCustomObject]@{
IPAddress = [System.Net.IPAddress]$Address
Port = $port
}
}
else
{
if ($Address.IndexOf("[") -ne -1)
{
[PSCustomObject]@{
IPAddress = [System.Net.IPAddress]$Address
Port = ($Address.Split("]")[-1]).TrimStart(":")
}
}
else
{
[PSCustomObject]@{
IPAddress = [System.Net.IPAddress]$Address
Port = $null
}
}
}
}
}
Process
{
$InputObject | ForEach-Object {
$address = Get-Address $_
$bytes = ([System.Net.IPAddress]$address.IPAddress).GetAddressBytes()
[Array]::Reverse($bytes)
$i = 0
$bytes | ForEach-Object -Begin {[bigint]$decimalIP = 0} `
-Process {$decimalIP += [bigint]$_ * [bigint]::Pow(256, $i); $i++} `
-End {[PSCustomObject]@{
Address = $address.IPAddress
Port = $address.Port
Hex = "0x$($decimalIP.ToString('x'))"}
}
}
}
}
</lang>
Parse an array of IP addresses in a text format:
<lang PowerShell>
$ipAddresses = "127.0.0.1","127.0.0.1:80","::1","[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80" | Get-IpAddress
$ipAddresses
</lang>
{{Out}}
<pre>
Address Port Hex
------- ---- ---
127.0.0.1 0x7f000001
127.0.0.1 80 0x7f000001
::1 0x1
::1 80 0x1
2605:2700:0:3::4713:93e3 0x260527000000000300000000471393e3
2605:2700:0:3::4713:93e3 80 0x260527000000000300000000471393e3
</pre>
The '''Address''' "property" is an object containing more information...
<lang PowerShell>
$ipAddresses[5].Address
</lang>
{{Out}}
<pre>
Address :
AddressFamily : InterNetworkV6
ScopeId : 0
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString : 2605:2700:0:3::4713:93e3
</pre>
... allowing for specific filtering:
<lang PowerShell>
$ipAddresses | where {$_.Address.AddressFamily -eq "InterNetworkV6" -and $_.Port -ne $null}
</lang>
{{Out}}
<pre>
Address Port Hex
------- ---- ---
::1 80 0x1
2605:2700:0:3::4713:93e3 80 0x260527000000000300000000471393e3
</pre>


=={{header|Python}}==
=={{header|Python}}==