简体   繁体   English

尝试侦听端口时没有任何反应

[英]nothing happens when trying to listen on a port

I'm trying to write a very simple program that just listens on a predefined port.here is the code: 我正在尝试编写一个非常简单的程序,它仅在预定义的端口上侦听。以下是代码:

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd;
struct addrinfo hints,*res;
memset(&hints,0,sizeof(hints));
hints.ai_family=AF_UNSPEC;
hints.ai_socktype=SOCK_STREAM;
hints.ai_flags=AI_PASSIVE;

getaddrinfo(NULL,"5050",&hints,&res); 
sockfd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);
bind(sockfd,res->ai_addr,res->ai_addrlen); //returns 0(success)
listen(sockfd,1);//returns 0(success)
return 0;
}

but there is no sign of listening anywhere.i used netstat -l command to check if the program is listening or not. 但是没有任何地方监听的迹象。我使用netstat -l命令检查程序是否在监听。

You are missing an accept() call. 您缺少一个accept()调用。

Also you are exiting from the program. 您也将从程序中退出。

The socket would be active for the duration of your process only. socket仅在您的过程中处于活动状态。

You have most of the parts but neglected to call accept(). 您拥有大部分内容,但忽略了调用accept()。 Without that your program probably just returns quickly without doing anything useful. 否则,您的程序可能会迅速返回而无用。

Your program does listen, but it exits immediately, so anything it has done vanishes into the ether. 您的程序确实在侦听,但它立即退出,因此它所做的任何事情都消失在以太坊中。 If you want to accept connections you will have to call accept() . 如果要接受连接 ,则必须调用accept()

You also need to error-check every one of those calls. 您还需要对每个调用进行错误检查。 You can't just assume they all succeeded. 您不能仅仅假设它们都成功。

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

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