How can I get the client IP address from a Sockets.TCPSocket object in Julia?

Viewed 101

In the documentation for HTTP.jl, the HTTP.serve function has an optional keyword argument tcpisvalid::Function (::TCPSocket) -> Bool which says it can be used to

check accepted connection before processing requests. e.g. to implement source IP filtering, rate-limiting, etc.

How can I get the client IP address from a TCPSocket object?

1 Answers

You can use the function Sockets.getpeername. According to the Sockets docs, the function signature is:

getpeername(sock::TCPSocket) -> (IPAddr, UInt16)

And the description is:

Get the IP address and port of the remote endpoint that the given socket is connected to. Valid only for connected TCP sockets.

So, for example, if you run your simple server with the following code...

HTTP.serve(app, "127.0.0.1", 8081; tcpisvalid=sock -> begin
    host, port = Sockets.getpeername(sock)
    println("Request from... $host:$port")
    true
end)

and then in a separate terminal run...

$ curl http://localhost:8081/

the output from your Julia server will be...

Request from... 127.0.0.1:40958
Related