【发布时间】:2014-12-09 21:36:10
【问题描述】:
我正在尝试编写一个非常简单的程序,它只侦听预定义的端口。代码如下:
#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;
}
但是在任何地方都没有监听的迹象。我使用 netstat -l 命令检查程序是否正在监听。
【问题讨论】:
-
听完后你需要一个循环来处理传入的连接。