在linux上我会这样做:
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(0);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR on binding");
*err = -2;
}
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sockfd, (struct sockaddr *)&sin, &len) == -1)
{
*err = -2;
perror("getsockname");
}
在Windows中我有:
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
//using 0 instead of DEFAULT_PORT gives me host not found.
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
socklen_t len = sizeof(result->ai_addr);
printf("Port number: %d", getsockname(ListenSocket, result->ai_addr, &len));
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
freeaddrinfo(result);
iResult = listen(ListenSocket, 4);
由于
答案 0 :(得分:0)
Windows的工作方式与Linux相同。
你的Linux代码不适用于Windows吗?真的应该可以编写适用于两者的代码,除了几个极端情况和初始化winsock(https://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx)。