我这两个函数用来连接和关闭网络接口设备。建立连接的函数有IP和端口做为参数,但是断开连接的函数没有,如果我同时和多台设备建立了连接,断开的时候要怎么做才能单独的断开其中一台设备或多台而不会影响到其它的。
apiStatus __declspec(dllexport) __stdcall DrfNetConnect (CString strIp, int port)
{
CApiSocket1* m_Sock = new CApiSocket1;
if(!m_Sock->Create())
{
m_Sock->ShutDown();
m_Sock->Close();
return -1;
}
else
{
// long tempIp;
// tempIp = inet_addr(strIp);
m_Sock->strIP = strIp;
m_Sock->port = port;
}
// CString tempIp;
// tempIp = "ping " + strIp;
// if(!system(tempIp))
// return -11;
/* ////////////////////////////////////////////
int ret,TimeOut=2000; //设置发送超时6秒
if(::setsockopt(*m_Sock,SOL_SOCKET,SO_SNDTIMEO,(char *)&TimeOut,sizeof(TimeOut))==SOCKET_ERROR)
{
return -1;
}
TimeOut=2000;//设置接收超时6秒
if(::setsockopt(*m_Sock,SOL_SOCKET,SO_RCVTIMEO,(char *)&TimeOut,sizeof(TimeOut))==SOCKET_ERROR)
{
return -1;
}
//设置非阻塞方式连接
unsigned long ul = 1;
ret = ioctlsocket(*m_Sock, FIONBIO, (unsigned long*)&ul);
if(ret==SOCKET_ERROR)return -1;
/*//////////////////////////////////////////////////////
sockaddr_in destIp;
destIp.sin_family = AF_INET;
destIp.sin_port = htons(port);
destIp.sin_addr.s_addr = inet_addr(strIp);
int Connectflag = m_Sock->Connect((const struct sockaddr*)&destIp,sizeof(destIp));
//SetTimer(hWnd,1,100,NULL);
// unsigned long ul = 1;
// int ret = ioctlsocket(*m_Sock, FIONBIO, (unsigned long*)&ul);
// if(ret==SOCKET_ERROR)return -1;
// SetTimer(hWnd, 1, 1000, (TIMERPROC)Timer2Proc);
//if(!m_Sock->Connect((const struct sockaddr*)&destIp,sizeof(destIp)))
/* struct timeval timeout ;
fd_set r;
FD_ZERO(&r);
FD_SET(*m_Sock, &r);
timeout.tv_sec = 3; //连接超时15秒
timeout.tv_usec =0;
ret = select(*m_Sock+1, 0, &r, 0, &timeout);
if ( ret <= 0 )
{
m_Sock->ShutDown();
::closesocket(*m_Sock);
return ret;
}
*/
if(Connectflag<=0)
{
// KillTimer(hWnd,1);
m_Sock->ShutDown();
m_Sock->Close();
delete m_Sock;
return -1;
}
// KillTimer(hWnd,1);
m_SockList.AddTail(m_Sock);
return drf_ok;
//
}
/*apiStatus ConnectState(CApiSocket1* m_Sock)
{
if(m_Sock->ConnectFlag != 1)
{
m_Sock->Close();
delete m_Sock;
return -2;
}
m_SockList.AddTail(m_Sock);
return drf_ok;
}*/
apiStatus __declspec(dllexport) __stdcall DrfNetDisconnect()
{
if(m_SockList.IsEmpty())
return -1;
while (!m_SockList.IsEmpty())
{
CApiSocket1 *m_Sock =(CApiSocket1*) m_SockList.RemoveHead();
// m_Sock->ConnectFlag = 0;
m_Sock->ShutDown();
m_Sock->Close();
delete m_Sock;
}
m_SockList.RemoveAll();
return drf_ok;
}