简体   繁体   English

(如何)我可以从套接字描述符中找到套接字类型吗?

[英](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. 我知道我可以使用getsockname找到套接字系列,但我找不到找到套接字类型的方法。

For instance, I want to find if this socket was open as UDP or TCP. 例如,我想查找此套接字是否作为UDP或TCP打开。 Thanks for any advice in advance. 感谢提前的任何建议。

YEH YEH

Since you mention getsockname I assume you're talking about POSIX sockets. 既然你提到了getsockname我假设你在谈论POSIX套接字。

You can get the socket type by calling the getsockopt function with SO_TYPE . 您可以通过使用SO_TYPE调用getsockopt函数来获取套接字类型。 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 . 有关更多信息,请参阅getsockopt()sys / socket.h的POSIX.1文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM