为什么我可以绑定到C中的(看似)无效端口?

Tim*_*Tim 2 c sockets

我使用BSD套接字在C中创建了一个基本的客户端和服务器.我能够绑定到65535以上的端口号,客户端可以连接到它.我在这做错了什么?

码:

int port = 999999;
...
serverAddr.sin_port = htons(port);
Run Code Online (Sandbox Code Playgroud)

Art*_*Art 5

因为htons采用16位参数,其输入将被截断.

试试这个,看看你得到了什么:

#include <stdio.h>
#include <arpa/inet.h>

int
main(int argc, char **argv)
{
        int foo = 999999;
        int bar = ntohs(htons(foo));

        printf("%d\n", bar);

        return 0;
}
Run Code Online (Sandbox Code Playgroud)