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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With