Reputation: 171
I am writing a program to capture socket network flow to display network activity. For this, I was wondering if there is any way I can determine the socket type from the socket descriptor.
I know that I can find socket family using getsockname but I could not find a way to find socket type.
For instance, I want to find if this socket was open as UDP or TCP. Thanks for any advice in advance.
YEH
Upvotes: 17
Views: 8989
Reputation: 2839
Since you mention getsockname
I assume you're talking about POSIX sockets.
You can get the socket type by calling the getsockopt
function with SO_TYPE
. For example:
#include <stdio.h>
#include <sys/socket.h>
void main (void) {
int fd = socket( AF_INET, SOCK_STREAM, 0 );
int type;
int length = sizeof( int );
getsockopt( fd, SOL_SOCKET, SO_TYPE, &type, &length );
if (type == SOCK_STREAM) puts( "It's a TCP socket." );
else puts ("Wait... what happened?");
}
Note that my example does not do any error checking. You should fix that before using it. For more information, see the POSIX.1 docs for getsockopt() and sys/socket.h.
Upvotes: 20