sockets - C on Windows: Bind to a free random port and get the port number -


on linux do:

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"); } 

in windows have:

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); 

thanks

windows works same linux here.

doesn't linux code work on windows? should possible write code works on both, apart couple of corner cases , initializing winsock (https://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -