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

谁说胖子不能爱 提交于 2019-11-30 01:58:41

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 && WSAGetLastError() == WSANOTINITIALISED){
        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
  • No, it is not possible to tell if WSAStartup() has already been called.

  • Yes, WSAStartup() can be called multiple times in a single process, as long as the requested version is supported by the WinSock DLL. Calls to WSAStartup() and WSACleanup() must be balanced.

  • WinSock initialization is a negotiated process; you are responsible for validating the info that WSAStartup() returns to make sure it meets your app's requirements.

  • Existing sockets are not affected by subsequent WSAStartup() calls.

  • Multiple sockets using different WinSock versions is allowed.

See the WSAStartup() documentation for more information.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!