Hello DaniWeb!

How can I check the state of a socket to see if it's connected or not?

SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
SOCKET client;

//I know that this isn't binded to an address but nevermind that.

client = accept(sock,NULL,NULL);

	if (client == HERE - Need to see if it's connected)
	{
		cout << "Connection established. \n";
	}

To accept connections you also have to call listen (http://www.mkssoftware.com/docs/man3/listen.3.asp).

The thread that called accept will be waiting until it receives a connection. If the socket receives a connection, it will return. If it returns -1, then an error has occured. Otherwise a connection was established/accepted and it will return the client's socket file descriptor (you can use it to send, recv, close etc.).

If you don't get an error code as a result of accept and you want to check connected status, try a read on the socket and check for errors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.