如何获取已连接客户端的 IP 地址?

How can I get a connected client's IP address?

如果我有一个超级简单的线程 TCP 服务器,例如:

USING: accessors io io.encodings.utf8 io.servers 
    io.sockets kernel prettyprint threads ;

: handle-client ( -- )
   remote-address . ;

: <my-server> ( -- threaded-server )
    utf8 <threaded-server>
        "server" >>name
        1234 >>insecure
        [ handle-client ] >>handler ;

: start-my-server ( -- )
    <my-server> [ start-server ] in-thread start-server drop ;

这只会将文本 remote-address 打印到客户端,这非常 很有帮助。那是因为 remote-address 是一个符号……它的值在哪里? remote-addressdocumentation 表示:

Variable holding the address specifier of the current client connection.

<threaded-server> 上的文档说:

The handler slot of a threaded server instance should be set to a quotation which handles client connections. Client handlers are run in their own thread, with the following variables rebound:

• input-stream
• output-stream
• local-address
remote-address
• threaded-server

太棒了!这意味着我可以获得客户的 IP。

然后链接到Address specifiers,貌似有关联,但是没说清楚如何从remote-address.

获取数据

如何获取客户端的 IP 地址?

nailed it in the comments: get 将采用 variableget 的值。

所以我的问题代码变成了:

: handle-client ( -- )
   remote-address get host>> print flush ;

: <my-server> ( -- threaded-server )
    utf8 <threaded-server>
        "server" >>name
        1234 >>insecure
        [ handle-client ] >>handler ;

: start-my-server ( -- )
    <my-server> [ start-server ] in-thread start-server drop ;