hummingbird-project / hummingbird

Lightweight, flexible HTTP server framework written in Swift
Apache License 2.0
1.16k stars 53 forks source link

How can I obtain the client's IP address? #535

Closed ilgrandeanonimo closed 1 month ago

ilgrandeanonimo commented 1 month ago

I need to get client IP address for a small whatsmyip, how can i obtain it? i tried looking into request headers, body, etc... but nothing

adam-fowler commented 1 month ago

You need to create a custom RequestContext that either stores the NIO Channel or the remote address and use that in your router

struct AppRequestContext: RequestContext {
    var coreContext: CoreRequestContextStorage
    let channel: Channel

    init(source: Source) {
        self.coreContext = .init(source: source)
        self.channel = source.channel
    }

    var remoteAddress: SocketAddress? { self.channel.remoteAddress }
}
let router = Router(context: AppRequestContext.self)
router.get("ip") { _, context in
    guard let ip = context.remoteAddress else { return "Couldn't get your IP" }
    return "Your IP is \(ip)"
}

I should probably include this as an example in the docs