How to get the client IP in a dart shelf-rpc server

1.2k views Asked by At

I have a dart web service application written with Shelf and Rpc apis.

I need to check the client Ip inside my api methods, but I cannot figure how.

The context method does not contain the HttpRequest .contentInfo property.

More, also the shelf Request object does not contain it, so also a middleware function would be of no use.

Anyone has an Idea on how to solve this problem?

2

There are 2 answers

1
BeatingToADifferentRobot On

You can do this by using the middleware concept of shelf. You can view an example logger middle ware here: https://www.crossdart.info/p/shelf/0.6.5+2/src/handlers/logger.dart.html. An example using the logger can be found here: https://github.com/dart-lang/shelf

In the middleware, you can find the ip address in the request object (which extends message). Message gives you access to the raw http header which contains the ip address. From there you can decide how you want to handle an invalid ip (throw an error, return a request with an error, etc.).

0
Huy Nguyen On

Here is how I get client IP:

FutureOr<Response> handleWs(Request request) {
    final clientAddress = (request.context['shelf.io.connection_info'] as 
    HttpConnectionInfo?)?.remoteAddress.address;
}

request is param when you handle shelf_router.Router(), like this:

final routerHandler = shelf_router.Router()
  ..get('/message', (request) => handleWs(request))