how to find a socket is existing or not ?

hi all,

I've written a Server socket program in C++, In my program Device Id is a unique one through which I accept the client connection. My code has to pass the below two test case.

1. If a client the the same device is connceted already, i've to reject the new conncetion.
2. If i remove the client network cable and try to conncet again it has to connect.

Can any one tell me how to do this?.

the major problem that i'm facing is in the 1st test case. The Function that i've written is




Code:
bool ValidatePrinterConnection(string sDeviceName)
{
char cMessage[1024];
memset(cMessage,0,1024);
string sRecvData;
struct fd_set readfds;
struct timeval time;
time.tv_sec = 20; time.tv_usec = 0;
bool bret = true;
int iSocketDesc = m_pConfig->GetSocketDesc1( m_sDeviceName ); //this will return the previous socket desc of the connceted client

for ( int i = 0; (i < 3 && bret == true) ; i++)
{
if ( iSocketDesc == 0 )
{
return false;
}
int iStatus=send(iSocketDesc,"R U connceted",100,0); // test data
if ( iStatus > 0 )
{
FD_ZERO(&readfds);
FD_SET(iSocketDesc, &readfds);
int iRetcode = select(iSocketDesc + 1 , &readfds,(fd_set*)NULL, (fd_set*)NULL, &time);
if ( iRetcode < 0 )
{
bret = false;
}
if ( iRetcode == 0)
{
bret = true;
}
if ( iRetcode == 1 )
{
bret = true;
}
}
else
{
bret = false;
}
}
return bret;
}

the above code is working fine in few time and giving false information in lot of times. Can any one tell me how to do it in a effective manner?


thanks in advance..
vijay
I couldn't understand what you are trying to do. You should post a better description of your program and what your are trying to achieve.

What's sure, however, is that this line:

int iStatus=send(iSocketDesc,"R U connceted",100,0); // test data

is buggy.

At best, it might send garbage on socket iSocketDesc, and at worse it can crash your program.
i've a socket desc, i want to check the status of the client using that socket desc. How to do that?

just help me how to do this?

i tried using send(); the send will fail only if the client is disconnceted properly, there is a case where due to network problem the client may be lost the conncetion(eg: manually remove the Client Network cable) in that case Send will not fail.

Tell me how to handle these two cases..
Detection of connection closed by remote host: http://stefan.buettcher.org/cs/conn_closed.html

The detection a broken link (e.g. cable disconnect) is a little more tricky. If you are under linux, you can change the TCP keepalive settings for your connection. See: http://tldp.org/HOWTO/html_single/TCP-Keepalive-HOWTO/ ; section 4 explains how to change the keepalive settings only for a specific connection (not system-wide).

Topic archived. No new replies allowed.