How to define source port of outgoing TCP socket in Dart

Viewed 75

I want to build a TCP connection sourceAddress:x-> host:port, how can I set x in dart?

The docs only describe Socket.connect(dynamic host, int port, {dynamic sourceAddress, Duration? timeout}, where it's not possible to define the local port x.

Appending the port to the sourceAddress variable here throws an invalid address error. Also RawSocket does not accept a local port parameter. I don't want to use a ServerSocket here, because I actually need to define the ports of both sides. To my understanding, this is only supported in dart for UDP 'connections':

var s = await RawDatagramSocket.bind(
        sourceAddress, x,
        reusePort: true);
s.send(...)

At least in python this is possible (from https://idea.popcount.org/2014-04-03-bind-before-connect/), where it's called bind-before-connect.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(sourceAddress, x)
s.connect(host, port)

Do you know if and how a similar result can be achieved in dart?

0 Answers
Related