不调用bind()的listen() [英] listen() without calling bind()

查看:192
本文介绍了不调用bind()的listen()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下操作:

int sockfd = socket(...);
listen(sockfd, 10);
accept(sockfd, ...);

所有调用均未失败,该程序刚刚开始阻塞,就好像我已经调用bind()一样.在这种情况下会发生什么?因为没有本地地址或端口,将永远不可能获得连接吗?还是隐式地为其分配了本地地址和端口,而现在正在监听这些地址和端口?如果是这样,我该如何检索这些内容?

None of the calls failed, and the program just started blocking as if I had called bind(). What will happen in this case? Will it just be impossible to ever receive a connection, since it has no local address or port? Or was it implicitly assigned a local address and port, and now it is listening on those? If so, how can I retrieve what those are?

推荐答案

这些调用是有效的,但是由于您没有显式绑定套接字,因此操作系统或系统库为您隐式分配了端口和默认绑定(完全是与您不先呼叫bind(2)而呼叫connect(2)时的情况相同).另外,由于您之前曾问过TCP方面的​​内容,所以我假设您在这里谈论的是Internet套接字.

The calls are working, but since you didn't bind the socket explicitly, the operating system or system library implicitly assigned a port and default binding for you (exactly the same as when you call connect(2) without calling bind(2) first). Also, since you asked about the TCP stuff earlier, I'm assuming you're talking about Internet sockets here.

找出操作系统将套接字绑定到的名称在不同的操作系统之间会有所不同,因此您必须查找特定的操作系统,但是大多数操作系统都提供了netstat或类似的工具,可用于查询哪些应用程序是监听哪个端口.

Finding out what name the OS bound the socket to varies between operating systems, so you will have to look for your specific OS, but most operating systems provide a netstat or similar tool that you can use to query which applications are listening on which ports.,

正如John在评论中提到的那样,您可以使用getsockname(2)查找绑定套接字的名称.这是一个简短的示例:

As John mentions in a comment, you can use getsockname(2) to find a bound socket's name. Here is a short example:

// ...

// Create socket and set it to listen (we ignore error handling for brevity)
int sock = socket(AF_INET, SOCK_STREAM, 0);
listen(sock, 10);

// Sometime later we want to know what port and IP our socket is listening on
socklen_t addr_size = sizeof(struct sockaddr_in);
struck sockaddr_in addr;
getsockname(sock, (struct sockaddr *)&addr, &addr_size);

addr现在将包含套接字正在监听的IP地址和端口.

addr will now contain the IP address and port that your socket is listening on.

这篇关于不调用bind()的listen()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆