forward method

  1. @override
Future<void> forward({
  1. bool? allowIPv6,
})
override

Apply default handler to connection.

TCP: Forward connection to requested host.

UDP: Forward connections to respective hosts.

Implementation

@override
Future<void> forward({
  bool? allowIPv6,
}) async {
  final client = await accept();

  final remote =  await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);

  client.where((event) => event == RawSocketEvent.read).listen((event) {
    final packet = client.receiveSocksPacket();

    if (packet == null)
      return;

    // Filter packets if client provided ip address and port.
    if (desiredAddress.address == '0.0.0.0' &&
        (desiredAddress != packet.clientAddress ||
            desiredPort != packet.clientPort))
              return;

    remote.send(packet.data, packet.remoteAddress, packet.remotePort);
  });

  remote.where((event) => event == RawSocketEvent.read).listen((event) {
    final datagram = remote.receive();

    if (datagram == null)
      return;

    final packet =
        SocksUpdPacket.create(datagram.address, datagram.port, datagram.data);

    client.send(packet.socksPacket, desiredAddress, desiredPort);
  });
}