Parse an IP Address: Difference between revisions

m
no edit summary
(Added Kotlin)
mNo edit summary
Line 1,088:
Port: 80
</lang>
 
=={{header|Julia}}==
<lang julia>
const testdata = ["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",
"::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80",
"1::", "[1::]:80", "::", "[::]:80"]
 
maybev4(ip) = search(ip, '.') > 0 && length(matchall(r":", ip)) < 2
maybev6(ip) = length(matchall(r":", ip)) > 1
 
function parseip(ip)
if (mat = match(r"^\[([:.\da-fA-F]+)\]:(\d+)$", ip))!= nothing ||
(mat = match(r"^([\d.]+)[:/](\d+)$", ip)) != nothing
port = mat.captures[2]
ip = mat.captures[1]
else
port = "none"
end
if maybev4(ip)
println("Processing ip v4 $ip")
iphex = hex(Int(Base.IPv4(ip)))
addresspace = "IPv4"
elseif maybev6(ip)
println("Processing ip v6 $ip")
iphex = hex(UInt128(Base.IPv6(ip)))
addresspace = "IPv6"
else
throw("Bad IP address argument $ip")
end
iphex, addresspace, port
end
 
for ip in testdata
hx, add, por = parseip(ip)
println("For input $ip, IP in hex is $hx, address space $add, port $por.")
end
</lang>
{{output}}
<pre>
Processing ip v4 127.0.0.1
For input 127.0.0.1, IP in hex is 7f000001, address space IPv4, port none.
Processing ip v4 127.0.0.1
For input 127.0.0.1:80, IP in hex is 7f000001, address space IPv4, port 80.
Processing ip v6 ::1
For input ::1, IP in hex is 1, address space IPv6, port none.
Processing ip v6 ::1
For input [::1]:80, IP in hex is 1, address space IPv6, port 80.
Processing ip v6 2605:2700:0:3::4713:93e3
For input 2605:2700:0:3::4713:93e3, IP in hex is 260527000000000300000000471393e3, address space IPv6, port none.
Processing ip v6 2605:2700:0:3::4713:93e3
For input [2605:2700:0:3::4713:93e3]:80, IP in hex is 260527000000000300000000471393e3, address space IPv6, port 80.
Processing ip v6 ::ffff:192.168.173.22
For input ::ffff:192.168.173.22, IP in hex is ffffc0a8ad16, address space IPv6, port none.
Processing ip v6 ::ffff:192.168.173.22
For input [::ffff:192.168.173.22]:80, IP in hex is ffffc0a8ad16, address space IPv6, port 80.
Processing ip v6 1::
For input 1::, IP in hex is 10000000000000000000000000000, address space IPv6, port none.
Processing ip v6 1::
For input [1::]:80, IP in hex is 10000000000000000000000000000, address space IPv6, port 80.
Processing ip v6 ::
For input ::, IP in hex is 0, address space IPv6, port none.
Processing ip v6 ::
For input [::]:80, IP in hex is 0, address space IPv6, port 80.
</pre>
 
=={{header|Kotlin}}==
4,102

edits