views:

33

answers:

1

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

+3  A: 

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.

Sam Hanes
Thank you so much! I will certainly do error checking.
YEH
getsockname() and getsockopt() are not specific to POSIX. Microsoft's Winsock API has them as well.
Remy Lebeau - TeamB
@Remy LebeauYes, they're both based on the BSD socket layer. There are some critical differences, but such simple usage of getsockopt() is likely to be the same.
Sam Hanes