     [ dup addrinfo-next swap addrinfo>addrspec ]
     [ ] unfold nip [ ] subset ;
 
+: prepare-resolve-host ( host serv passive? -- host' serv' flags )
+    >r
+    >r string>char-alien r>
+    dup integer? [ port-override set f ] [ string>char-alien ] if
+    r> AI_PASSIVE 0 ? ;
+
 M: object resolve-host ( host serv passive? -- seq )
-    >r dup integer? [ number>string ] when
-    "addrinfo" <c-object>
-    r> [ AI_PASSIVE over set-addrinfo-flags ] when
-    PF_UNSPEC over set-addrinfo-family
-    IPPROTO_TCP over set-addrinfo-protocol
-    f <void*> [ getaddrinfo addrinfo-error ] keep *void*
-    [ parse-addrinfo-list ] keep
-    freeaddrinfo ;
+    [
+        prepare-resolve-host
+        "addrinfo" <c-object>
+        [ set-addrinfo-flags ] keep
+        PF_UNSPEC over set-addrinfo-family
+        IPPROTO_TCP over set-addrinfo-protocol
+        f <void*> [ getaddrinfo addrinfo-error ] keep *void*
+        [ parse-addrinfo-list ] keep
+        freeaddrinfo
+    ] with-scope ;
 
 M: object host-name ( -- name )
     256 <byte-array> dup dup length gethostname


M: inet6 parse-sockaddr
    >r dup sockaddr-in6-addr r> inet-ntop
    swap sockaddr-in6-port ntohs <inet6> ;

: addrspec-of-family ( af -- addrspec )
    {

    "0.0.0.0" or
    rot inet-pton *uint over set-sockaddr-in-addr ;

SYMBOL: port-override

: (port) port-override get [ ] [ ] ?if ;

M: inet4 parse-sockaddr
    >r dup sockaddr-in-addr <uint> r> inet-ntop
    swap sockaddr-in-port ntohs (port) <inet4> ;

M: inet6 inet-ntop ( data addrspec -- str )
    drop 16 memory>string 2 <groups> [ be> >hex ] map ":" join ;
