I'm trying to create helper functions to setup the keep alive of a tcp socket. The setsockopt function accepts a pointer to a value. My question is, does the value have to stay valid for the entire lifetime of the socket or only while executing this function?
This is the example I use: https://github.com/espressif/esp-idf/blob/ac315adc2c76309b8b9c82e166f03891ad2031bb/examples/protocols/sockets/tcp_server/main/tcp_server.c
To clarify my question, which of the following examples would be correct?
Example 1:
void SetKeepAlive(int handle, int enable, int idle, int interval, int count)
{
// Set tcp keepalive option
setsockopt(handle, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(int));
setsockopt(handle, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(int));
setsockopt(handle, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(int));
setsockopt(handle, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(int));
}
Example 2:
int _enable;
int _idle;
int _interval;
int _count;
void SetKeepAlive2(int handle, int enable, int idle, int interval, int count)
{
_enable = enable;
_idle = idle;
_interval = interval;
_count = count;
// Set tcp keepalive option
setsockopt(handle, SOL_SOCKET, SO_KEEPALIVE, &_enable, sizeof(int));
setsockopt(handle, IPPROTO_TCP, TCP_KEEPIDLE, &_idle, sizeof(int));
setsockopt(handle, IPPROTO_TCP, TCP_KEEPINTVL, &_interval, sizeof(int));
setsockopt(handle, IPPROTO_TCP, TCP_KEEPCNT, &_count, sizeof(int));
}
The parameter to
setsockoptis not expected to persist forever, and would be copied by the call.Note, though, that this might not extend to anything a socket option might point to (though the only cases I did find (
SO_ATTACH_FILTER/SO_ATTACH_REUSEPORT_CBPF) do copy the internally pointed to object, and it's reasonable to expect most similar cases to behave the same).I would generally expect anything requiring an extended lifetime to be documented as such.