c/c++检测sock fd网络连接描述符是否有效

xingyun86 2019-8-23 1353

c/c++检测sock fd网络连接描述符是否有效(Linux)

int SocketConnected(int sockfd)
{
    if (sockfd == (-1))
    {
        return 0;
    }
    struct tcp_info info = {0};
    int size = sizeof(info);
    getsockopt(sockfd, IPPROTO_TCP, TCP_INFO, &info, (socklen_t*)& size);
    if ((info.tcpi_state == TCP_ESTABLISHED))
    {
        printf("socket connected\n"); 
        return 1;
    }
    else
    {
        printf("socket disconnected\n"); 
        return 0;
    }
}

c/c++检测sock fd网络连接描述符是否有效(Windows Linux通用)

#include <mutex>
std::mutex g_locker;
// 其它地方与socket相关的调用使用宏
#define SEND_WIRH_LOCK(locker,s,buf,len,flags) locker.lock();send(s,buf,len,flags);locker.unlock();
#define RECV_WIRH_LOCK(locker,s,buf,len,flags) locker.lock();recv(s,buf,len,flags);locker.unlock();
int SocketConnected(int sockfd)
{
    if (sockfd == (-1))
    {
        return 0;
    }
    bool state = false;
    char buffer[1] = { 0 };
    unsigned long ul_value = 0;
    g_locker.lock();
    ul_value = 1;
    ioctlsocket(sockfd, FIONBIO, (unsigned long*)&ul_value);
    /////////////////////////////////
    // MSG_PEEK
    // Peeks at the incoming data. The data is copied into the buffer, 
    // but is not removed from the input queue. The function subsequently 
    // returns the amount of data that can be read in a single call to the 
    // recv (or recvfrom) function, which may not be the same as the total 
    // amount of data queued on the socket. The amount of data that can actually 
    // be read in a single call to the recv (or recvfrom) function is limited to 
    // the data size written in the send or sendto function call.
    recv(sockfd, buffer, 1, MSG_PEEK);
    state = (WSAECONNRESET != WSAGetLastError());
    ul_value = 0;
    ioctlsocket(sockfd, FIONBIO, (unsigned long*)&ul_value);
    g_locker.unlock();
    if (state == true)
    {
        printf("===socket connected\n");
        return 1;
    }
    else
    {
        printf("===socket disconnected\n");
        return 0;
    }
}


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回