fullstorydev / grpcurl

Like cURL, but for gRPC: Command-line tool for interacting with gRPC servers
MIT License
10.36k stars 497 forks source link

How to specify grpcurl's (client's) port? #332

Open murfel opened 1 year ago

murfel commented 1 year ago

My sample grpc application uses host+port as a client id. However, grpcurl seems to make calls from a random port each time. I don't seem to find any flag in grpcurl -help that would allow to connect from a specific port. Am I missing something out? Thanks!

jhump commented 1 year ago

@murfel, it is not grpcurl picking a random port, it is the operating system. This is standard behavior for the client side of TCP connections: https://en.wikipedia.org/wiki/Ephemeral_port.

While some TCP libraries do allow the caller to choose the client port, usage is exceedingly rare, especially with standard protocols like HTTP. One major issue with doing so is port conflicts: the tuple of (client IP, client port, server IP, server port) must be unique for a TCP connection. So if you had more than one process on the host connecting to the same server IP+port with the same client port, or even trying to open multiple connections inside the same process, only the first could succeed because all subsequent connections conflict with the first one. This is the reason why the operating system picks a client port seemingly at random (never fear -- if a random selection was an actual conflict with an existing connection, a different port would be chosen) and why a fairly large chunk of the port space is reserved for ephemeral ports (in practice usually 32768–60999, but 49152–65535 per IETF RFC 6335).

Is "host+port" meant to represent port on which the client process is listening, also acting as a server (I.e. if they are all servers that talk to one another)? I have seen that technique commonly used when implementing things like affinity. If that is the intent, you should probably be including that information in each request, like as "client ID" metadata, instead of relying on properties of the TCP socket. In other words, each client advertises its ID with each request.