Reputation: 2004
Given only an existing/open socket handle, how can I determine whether the socket is a connection-oriented socket under Linux? I am searching for something like the WSAPROTOCOL_INFO
under Windows, which I can retrieve using getsockopt
.
Thanks in advance, Christoph
Upvotes: 1
Views: 602
Reputation: 19761
int sock_type;
socklen_t sock_type_length = sizeof(sock_type);
getsockopt(socket, SOL_SOCKET, SO_TYPE, &sock_type, &sock_type_length);
if (sock_type == SOCK_STREAM) {
// it's TCP or SCTP - both of which are connection oriented
} else if (sock_type == SOCK_DGRAM) {
// it's UDP - not connection oriented
}
I suppose this is slightly simplistic, as there can be other protocols that can be stream or datagram, but this code is almost always what you want.
Upvotes: 3
Reputation: 4168
Taken from here:
Socket options
These socket options can be set by using setsockopt(2) and read with getsockopt(2) with the socket level set to SOL_SOCKET for all sockets:
...
SO_PROTOCOL (since Linux 2.6.32) Retrieves the socket protocol as an integer, returning a value such as IPPROTO_SCTP. See socket(2) for details. This socket option is read-only.
SO_TYPE Gets the socket type as an integer (e.g., SOCK_STREAM). This socket option is read-only.
To correct the solution provided by xaxxon, the code has to be:
int sock_type;
socklen_t sock_type_length = sizeof(sock_type);
getsockopt(socket, SOL_SOCKET, SO_TYPE, &sock_type, &sock_type_length);
if (sock_type == SOCK_STREAM) {
getsockopt(socket, SOL_SOCKET, SO_PROTOCOL, &sock_type, &sock_type_length);
if (sock_type == IPPROTO_TCP) {
// it's TCP
} else {
// it's SCTP
}
} else if (sock_type == SOCK_DGRAM) {
// it's UDP
}
Upvotes: 1