【问题标题】:Why is the Mac OS specified TCP port not listening?为什么 Mac OS 指定的 TCP 端口不监听?
【发布时间】:2019-10-24 05:50:58
【问题描述】:

我有问题。

我用 C++ 编写程序,指定端口 60000。

m_pConn.sin_port = htons( 60000 );

然后,当程序(TCPFileSe)启动时,我注意到 LISTENING 端口不是 60000。

这是我的监听端口列表..

christof-kims-Mac:~ christof-kim$ lsof -i | grep 听 rapportd 639 christof-kim 3u IPv4 0x1b8366a443833957 0t0 TCP *:49234 (LISTEN) rapportd 639 christof-kim 4u IPv6 0x1b8366a4437c0def 0t0 TCP *:49234 (LISTEN) **TCPFileSe 24454 christof-kim 3u IPv4 0x1b8366a446445957 0t0 TCP *:50087 (LISTEN)**

当我第二次开始编程时..

christof-kims-Mac:~ christof-kim$ lsof -i | grep 听 rapportd 639 christof-kim 3u IPv4 0x1b8366a443833957 0t0 TCP *:49234 (LISTEN) rapportd 639 christof-kim 4u IPv6 0x1b8366a4437c0def 0t0 TCP *:49234 (LISTEN) **TCPFileSe 24647 christof-kim 3u IPv4 0x1b8366a446445957 0t0 TCP *:50117 (LISTEN)**

我不明白为什么 LISTENING 端口不是 60000。

你能帮我解释为什么 LISTENING 端口是 50087、50117 吗? 或者,Mac OS 不支持指定端口???

我需要指定端口(例如 60000)。

此代码只是为 Mac OS 10.13.6 编写的 c++ 语言。 我在 Mac OS 控制台线工具上试过了。

sockaddr_in m_pConn;

m_pConn.sin_family = AF_INET;
m_pConn.sin_addr.s_addr = inet_addr( "0.0.0.0" );
m_pConn.sin_port = htons( 60000 );

bind(m_nSocket, (struct sockaddr *) &m_pConn, sizeof(m_pConn));
socklen_t len = sizeof(m_pConn);

// Listen on the socket.
if ( listen( m_nSocket, 1 ) == -1 )
    printf( "Error listening on socket.\n");

【问题讨论】:

  • 当bind() 返回 -1 时,errno 是什么?
  • 当我返回 bind -1 时我错过了 errno。
  • 我解决了这个问题!!谢谢用户207421。

标签: c++ macos tcp port listen


【解决方案1】:

问题是我使用了using namespace std。

//using namespace std;

所以,我添加了以下代码,然后它就可以工作了。

using std::ifstream;
using std::ios;

也许问题与此有关: Compiling code that uses socket function bind() with libcxx fails

【讨论】:

  • 使用std和bind时,端口监听不匹配。
  • @LightnessRacesinOrbit 他调用的是std::bind(),这是一个C++库的东西,而不是::bind(),它是TCP API。
  • 我想可能是一个古老的 stdlib 实现(即 pre this)
  • 但是still shouldn't compile 因为没有返回类型可以推断。
猜你喜欢
  • 2011-05-24
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
相关资源
最近更新 更多