eclipse-paho / paho.mqtt.golang

Other
2.77k stars 534 forks source link

How to get remote addr and local addr when connected #595

Closed oyljerry closed 2 years ago

oyljerry commented 2 years ago

Hi All:
After mqtt is connected, is there any way to get remote address (IP:Port) and local address (IP:Port) from this library? Thanks.

MattBrittan commented 2 years ago

The connection (client.conn) is not exported and no functions are currently provided that would give you access to the info you want - so no (providing access would introduce some complexity because the library supports automatic reconnections). I guess you could implement your own SetCustomOpenConnectionFn and get the info that way. This is something that could be added but seems pretty niche; may I ask what your use-case is?

oyljerry commented 2 years ago

Thanks for reply. Because I want to collect the information about current connection, So I need the remote address and local address.

"providing access would introduce some complexity because the library supports automatic reconnections" --> I think it can use a variable to store these, every time connected, refresh it. when disconnected, clear it.

oyljerry commented 2 years ago

@MattBrittan Is it ok to export client.conn, then others can use it to get more information about connection?

MattBrittan commented 2 years ago

No - it could not be accessed in a thread safe way (can be overwritten at any time by the reconnect code).

oyljerry commented 2 years ago

@MattBrittan I checked openConnection, I think here we just need to save (remoteAddr and localAddr) before return conn in it. It seems reimplement SetCustomOpenConnectionFn is a bit duplicate.

MattBrittan commented 2 years ago

Implementing the connection function involves a little bit of copying/pasting but is easily done within your own code. I'm reluctant to add complexity to the library for a fairly niche requirement when there is a workaround (you have not explained what you are using this info for so it's difficult to see if it would be of use to anyone else).

oyljerry commented 2 years ago

@MattBrittan I want this info is that the endpoint may have LB, and there are several IPs for it. So I want to get the remote addr and local addr of current MQTT connection. once more, It may be also useful when diagnostic network.

MattBrittan commented 2 years ago

I'm going to close this issue. There is a fairly simple work around (implement your own SetCustomOpenConnectionFn) and capture the address you want in that (this should only take a couple of minutes to do). The reasons I'm not adding this to the library are: