简体   繁体   English

检查套接字是否正在C中侦听

[英]Check if socket is listening in C

在遍历套接字文件描述符时,如何检查其中一个是否来自被动套接字(侦听连接)?

This can be checked with getsockopt ( SO_ACCEPTCONN ). 可以使用getsockoptSO_ACCEPTCONN )检查。 For example: 例如:

#include <sys/socket.h>

int val;
socklen_t len = sizeof(val);
if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &val, &len) == -1)
    printf("fd %d is not a socket\n", fd);
else if (val)
    printf("fd %d is a listening socket\n", fd);
else
    printf("fd %d is a non-listening socket\n", fd);

You can't really tell. 你无法真正说出来。 You have to keep track of it yourself, and when you want to check if a socket is the listening socket you compare with the one you have saved. 您必须自己跟踪它,并且当您想要检查套接字是否是您已保存的套接字的监听套接字时。

Strictly speaking, you could try performing an operation on the socket which would incidentally determine what type of socket it is, like trying to accept a connection from it. 严格地说,你可以尝试在套接字上执行一个操作,这会偶然确定它是什么类型的套接字,比如尝试接受来自它的连接。 If accept() fails with EINVAL, that's a pretty good sign that it isn't listening. 如果accept()因EINVAL而失败,这是一个非常好的迹象,表明它没有收听。 :) :)

Keeping track of which sockets are which is a better solution overall, though. 但是,跟踪哪个套接字是一个更好的解决方案。 Unless you're building a really trivial application, chances are that you'll need to keep some sort of additional data on each socket anyway. 除非你正在构建一个非常简单的应用程序,否则你可能需要在每个套接字上保留一些额外的数据。

You can run in the command line (on a Mac/Linux enviroment): 您可以在命令行中运行(在Mac / Linux环境中):

lsof -i

and/or (Linux/Mac/Windows enviroment) 和/或(Linux / Mac / Windows环境)

netstat -a

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

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