diff --git a/NEWS.md b/NEWS.md index 3fb47f9296734..ff1c2bcec40a1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -81,6 +81,11 @@ Standard library changes * `quantile` now accepts in all cases collections whose `eltype` is not a subtype of `Number` ([#30938]). +#### Sockets + +* Added `InetAddr` constructor from `AbstractString`, representing IP address, and `Integer`, + representing port number ([#31459]). + #### Miscellaneous * Since environment variables on Windows are case-insensitive, `ENV` now converts its keys diff --git a/stdlib/Sockets/src/IPAddr.jl b/stdlib/Sockets/src/IPAddr.jl index c77e1f9887064..756c2f67d10e9 100644 --- a/stdlib/Sockets/src/IPAddr.jl +++ b/stdlib/Sockets/src/IPAddr.jl @@ -271,7 +271,35 @@ struct InetAddr{T<:IPAddr} port::UInt16 end +""" + InetAddr(ip::IPAddr, port) -> InetAddr + +Return an `InetAddr` object from ip address `ip` and port number `port`. + +# Examples +```jldoctest +julia> Sockets.InetAddr(ip"127.0.0.1", 8000) +Sockets.InetAddr{IPv4}(ip"127.0.0.1", 8000) +``` +""" InetAddr(ip::IPAddr, port) = InetAddr{typeof(ip)}(ip, port) + +""" + InetAddr(str::AbstractString, port) -> InetAddr + +Return an `InetAddr` object from ip address `str` formatted as [`AbstractString`](@ref) +and port number `port`. + +!!! compat "Julia 1.2" + This constructor requires at least Julia 1.2. + +# Examples +```jldoctest +julia> Sockets.InetAddr("127.0.0.1", 8000) +Sockets.InetAddr{IPv4}(ip"127.0.0.1", 8000) +``` +""" +InetAddr(str::AbstractString, port) = InetAddr(parse(IPAddr, str), port) function show(io::IO, addr::InetAddr) show(io, typeof(addr)) print(io, "(") diff --git a/stdlib/Sockets/test/runtests.jl b/stdlib/Sockets/test/runtests.jl index 018b00b90f463..67b57d56d5bac 100644 --- a/stdlib/Sockets/test/runtests.jl +++ b/stdlib/Sockets/test/runtests.jl @@ -66,6 +66,9 @@ end @test inet.port == 1024 str = "Sockets.InetAddr{$(isdefined(Main, :IPv4) ? "" : "Sockets.")IPv4}(ip\"127.0.0.1\", 1024)" @test sprint(show, inet) == str + inet = Sockets.InetAddr("127.0.0.1", 1024) + @test inet.host == ip"127.0.0.1" + @test inet.port == 1024 end @testset "InetAddr invalid port" begin @test_throws InexactError Sockets.InetAddr(IPv4(127,0,0,1), -1)