【问题标题】:How to get the client IP adress using HTTP.jl如何使用 HTTP.jl 获取客户端 IP 地址
【发布时间】:2021-07-05 19:44:47
【问题描述】:

我正在尝试从 http 请求中获取客户端请求和 IP 地址到我的 HTTP.jl 服务器(基于 basic server example in the docs)。

using HTTP
using Sockets

const APP = HTTP.Router()

# My request handler function can see the request's method
# and target but not the IP address it came from
HTTP.@register(APP,"GET","/",req::HTTP.Request -> begin
    println("$(req.method) request to $(req.target)")
    "Hello, world!"
end)

HTTP.serve(
    APP,
    Sockets.localhost,
    8081;
    # My tcpisvalid function can see the client's
    # IP address but not the HTTP request
    tcpisvalid=sock::Sockets.TCPSocket -> begin
        host, port = Sockets.getpeername(sock)
        println("Request from $host:$port")
        true
    end
)

我最好的猜测是有一种方法可以将 TCPSocket.buffer 解析为 HTTP 请求,但我找不到任何方法来做到这一点。

您能否建议一种从TCPSocket 获取HTTP.Request 的方法或解决此问题的不同方法?

提前致谢!

【问题讨论】:

  • 听起来您可能想为 HTTP.jl 打开一个问题/功能请求。许多像这样的框架会将这种额外的元数据与请求一起发送为“REMOTE_ADDR”,也许 HTTP.jl 也应该这样做。
  • 好主意,谢谢!

标签: http tcp ip julia webserver


【解决方案1】:

路由器(APP)是一个(集合)“请求处理程序”,它只能访问HTTP.Request——您无法从中获取流。相反,您可以定义一个“流处理程序”,将其传递给流。从流中,您可以使用 Sockets.getpeername 获取客户端的 IP 地址(在 HTTP.Stream 上调用时需要 HTTP.jl 版本 0.9.7,如下例所示)。

using HTTP, Sockets

const APP = HTTP.Router()

function request_handler(req::HTTP.Request)
    println("$(req.method) request to $(req.target)")
    return "Hello, world!"
end

HTTP.@register APP "GET" "/" request_handler

function stream_handler(http::HTTP.Stream)
    host, port = Sockets.getpeername(http)
    println("Request from $host:$port")
    return HTTP.handle(APP, http) # regular handling
end

# HTTP.serve with stream=true to specify that stream_handler is a function
# that expects a HTTP.Stream as input (and not a HTTP.Request)
HTTP.serve(stream_handler, Sockets.localhost, 8081; stream=true) # <-- Note stream=true

# or HTTP.listen
HTTP.listen(stream_handler, Sockets.localhost, 8081)

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 2012-02-16
    • 2010-12-11
    • 2016-01-12
    • 2017-12-20
    • 2019-01-14
    • 2015-12-20
    • 2016-03-29
    • 1970-01-01
    相关资源
    最近更新 更多