我正在尝试编写一些套接字应用程序并遇到问题。我希望操作系统为我的地址选择随机的可用端口号。但我收到端口号 = 0。我做错了什么?
struct sockaddr_in addr;
socklen_t addrLen;
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
ThreadError("Failed to create data channel socket");
}
addr.sin_family = AF_INET;
addr.sin_port = 0; // pick random free port
addr.sin_addr.s_addr = srvAddr; // = inet_addr(127.0.0.1)
if (bind(fd, (const struct sockaddr *)&addr, sizeof(addr)) == -1) {
ThreadError("Failed to bind data channel");
}
if (getsockname(fd, (struct sockaddr *)&addr, &addrLen) == -1) {
ThreadError("getsockname() failed");
}
if (listen(fd, 1) == -1) {
ThreadError("Failed to set socket to listen mode");
}
// addr.sin_port == 0