[WinSock] find unused socket?

SOCKET sock[32]
what is the value of for example sock[3]? or better said, how do I know that this socket is not taken? also what value it has when I close socket using
closesocket(sock[3])

I need this, because I need to find a "empty" socket that is not connected to any client on my server when a client connects
You don't if you don't properly initialize everything.

1
2
3
4
5
6
7
8
9
10
11
12
SOCKET sock[32] = { INVALID_SOCKET };  // All elements are invalid

...

sock[3] = socket( ... );  // Create a socket (well, try to, at least)

...

if (sock[3] != INVALID_SOCKET) 
{
  // flush and closesocket() here
}

If you know that there is no data to flush, just call closesocket(). Nothing bad will happen if it gets an INVALID_SOCKET as argument.

You might want to look through some stuff on using sockets:
http://www.google.com/search?btnI=1&q=msdn+Winsock+Reference
https://www.google.com/search?q=winsock+tutorial

Hope this helps.
thanks, well, there's another problem now, I'm not initializing sockets as
SOCKET sock[32]
but
1
2
3
SOCKET *sock;
//a lot of code
sock = new SOCKET[iSockets];


how do I initialize those as INVALID_SOCKET without a loop?
> how do I initialize those as INVALID_SOCKET without a loop?

Use std::vector<SOCKET>. With arrays, a loop is required.

1
2
3
4
5
6
7
8
9
10
11
12
constexpr std::size_t N = 100 ;

SOCKET sock[100] ;
std::uninitialized_fill_n( sock, N, INVALID_SOCKET ) ;

std::size_t iSockets ;
std::cin >> iSockets ;

SOCKET* sock2 = new SOCKET[iSockets] ;
std::uninitialized_fill_n( sock2, iSockets, INVALID_SOCKET ) ;

std::vector<SOCKET> sock3( iSockets, INVALID_SOCKET ) ;



@ OP: Without context not wanting to use a loop seems like an arbitrary restriction. So I have to ask; why?
@JLBorges Thanks!
@Computergeek01 sorry, I didnt understand a word you said :/
I was just wondering why it is you didn't want to use a loop to initialize your sockets. I can't think of a good reason to avoid them.
I dont find it a efficient way to initialize variables, i dont know why, maybe there's better way to do it
There is no way to avoid it except for the example on the first line of code I gave you.

Otherwise you must use a loop.

It is no less efficient than having a zillion variables individually initialized. The initialization must occur at some point.

Edited -- you must use a loop or give every value in the initializer. Thanks JLBorges!
Last edited on
ok thanks
> There is no way to avoid it except for the example on the first line of code I gave you.
> SOCKET sock[32] = { INVALID_SOCKET }; // All elements are invalid

This would initialize sock[0] with INVALID_SOCKET and the remaining elements of the array with zeroes.
Yoinks!
Topic archived. No new replies allowed.