socketsstreamserverfactor-lang

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


If I have a Super Simple Threaded TCP Server like:

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 ;

This will just print the text remote-address to the client, which is very helpful. That's because remote-address is a symbol... where's its value? The documentation for remote-address says:

Variable holding the address specifier of the current client connection.

And the docs on <threaded-server> say:

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

Great! That means I can get at a client's IP.

Then it links to Address specifiers, which seems to be related, but doesn't clearly explain how to get data from remote-address.

How can I get a client's IP address?


Solution

  • @fede s. nailed it in the comments: get will take a variable and get its value.

    So my code from the question becomes:

    : 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 ;