Is it possible to tell if WSAStartup has been called in a process?

后端 未结 2 1059
太阳男子
太阳男子 2020-12-28 08:43

I\'ve started writing an ActiveX control that makes use of sockets.

Applications that use this control may or may not also use sockets. Is it possible for my control

2条回答
  •  臣服心动
    2020-12-28 09:13

    Yes it is possible.

    And here is how it's done.

    bool WinsockInitialized()
    {
        SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (s == INVALID_SOCKET){
            return false;
        }
    
        closesocket(s);
        return true;
    }
    
    int main()
    {
        //...
        if ( !WinsockInitialized() )
           // Init winsock here...
    
        // Carry on as normal.
        // ...         
    }
    

    But it's not really necessary to do this. It's quite safe to call WSAStartup at any time. It's also safe to end each successful call to WSAStartup() with a matching call to WSACleanup().

    e.g.

    // socket calls here would be an error, not initialized
    WSAStartup(...)
    // socket calls here OK
    
    WSAStartup(...)
    // more socket calls OK
    
    WSACleanup()
    // socket calls OK
    
    WSACleanup()
    
    // more socket calls error, not initialized
    

提交回复
热议问题