sumit kang
sumit kang

Reputation: 476

How to check if a socket is connected or not

I am using this piece of code to send socket command which i got from this site.

void SendExternalCommand(std::string Cmd,const std::string HostName,const int Port)
{

boost::asio::io_service io;
boost::asio::ip::tcp::socket socket(io);
boost::asio::ip::tcp::endpoint   
e(boost::asio::ip::address::from_string(HostName), Port);
socket.open(boost::asio::ip::tcp::v4());
socket.connect(e) ;
socket.write_some(boost::asio::buffer(Cmd));
socket.send(boost::asio::buffer(Cmd));
}

How can i check if a socket is available or not.

i tried doing if(!socket.open(boost::asio::ip::tcp::v4())) but it does not work.

Upvotes: 1

Views: 8324

Answers (2)

Jens
Jens

Reputation: 9406

boost::asio::ip::tcp::socket has a is_open() method which seems to give the result.

However, you should be aware that between calling is_open and then sending data with send, the socket can be closed. In addition, TCP write functions usually return immediately after copying the data into the kernel buffer. If sending fails, you will get an error at the next send.

In general, it is also a good idea to read from a socket because that is the reliable way to detect a closed connection. As part of the shutdown process, a call to recv will return with a result of 0 when the client has closed the connection. I don't know what boost::asio implements, so it is good idea to check the documentation.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

You can try to use getsockopt like this:

int err = 0;
socklen_t size = sizeof (err);
int check = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &err, &size);
if (check != 0) 
{
   //some code
}

Also refer: How can I check is a socket is still open?

Upvotes: 0

Related Questions