dartdart-shelfdart-server

How to get the IP address of the user with shelf in dart server side?


In general, I can get the IP address of the request sender by:

import 'dart:io';

Future<void> main() async {
  final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
  print('Server listening on ${server.address}');

  await for (var request in server) {
    final clientAddress = request.connectionInfo?.remoteAddress;
    print('Received request from ${clientAddress?.address}');

    // Handle the request
    request.response.write('Hello, world!');
    await request.response.close();
  }
}

But I am using the shelf method. My code look like this:

import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart' as shelf_router;
import 'package:shelf_static/shelf_static.dart' as shelf_static;

Future main(List<String> arguments) async {
  final cascade = Cascade().add(_staticHandler).add(_router);
  final server = await shelf_io.serve(logRequests().addHandler(cascade.handler), InternetAddress.anyIPv4, 8080);
}

final _staticHandler = shelf_static.createStaticHandler('public', defaultDocument: 'index.html');
final _router = shelf_router.Router()
  ..get('/get', (Request request) async {
    return Response(HttpStatus.ok, headers: {}, body: 'get');
  })
  ..post('/post', (Request request) async {
    return Response(HttpStatus.ok, headers: {}, body: 'post');
  })
  ..all('/<ignored|.*>', (Request request) {
    return Response(HttpStatus.notFound);
  });

How to get the user IP address with my code? I tried using

  final clientAddress = request.headers['x-forwarded-for']?.split(',').first.trim() ?? (request.context['shelf.io.connection'] as HttpConnectionInfo?)?.remoteAddress;

but the result is null.


Solution

  • After I tried to find it by seeing all parameters of each request parameter, I got it!

      final clientAddress = (request.context['shelf.io.connection_info'] as HttpConnectionInfo?)?.remoteAddress.address;