Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(How) Can I find the socket type from the socket descriptor?

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

like image 753
YEH Avatar asked Jul 10 '10 03:07

YEH


People also ask

What is the data type of socket descriptor?

In UNIX, a socket descriptor is represented by a standard file descriptor. This means you can use any of the standard UNIX file I/O functions on sockets. This isn't true on Windows, so we simply avoid these functions to maintain portability.

How do I identify a socket?

A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints.

What is a socket file descriptor?

Each socket within the network has a unique name associated with it called a socket descriptor—a fullword integer that designates a socket and allows application programs to refer to it when needed.

Are sockets available through file descriptors Linux?

There is no difference between a socket (descriptor) and a file descriptor(s). A socket is just a special form of a file. For example, you can use the syscalls used on file descriptors, read() and write(), on socket descriptors.


1 Answers

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.

like image 95
Sam Hanes Avatar answered Sep 22 '22 01:09

Sam Hanes