windows 是否可以判断进程中是否已调用 WSAStartup?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1869689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:33:26  来源:igfitidea点击:

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

windowswinsock2windows-socket-apiwsastartup

提问by Matt

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

我已经开始编写一个使用套接字的 ActiveX 控件。

Applications that use this control may or may not also use sockets. Is it possible for my control to tell whether WSAStartup has been called?

使用此控件的应用程序可能也可能不使用套接字。我的控件是否可以判断是否已调用 WSAStartup?

If not, call it. A little test reveals that calling WSAStartup multiple times is tollerated. But what happens if a different winsock version is requested? will this break other parts of the application?

如果没有,就调用它。一个小测试表明多次调用 WSAStartup 是可以容忍的。但是如果请求不同的 winsock 版本会发生什么?这会破坏应用程序的其他部分吗?

回答by Matt

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().

但实际上没有必要这样做。随时调用 WSAStartup 是非常安全的。使用对 WSACleanup() 的匹配调用来结束对 WSAStartup() 的每次成功调用也是安全的。

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

回答by Remy Lebeau

  • 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.

  • 不,无法判断是否WSAStartup()已经被调用。

  • WSAStartup()可以,只要 WinSock DLL 支持请求的版本,就可以在单个进程中多次调用。调用WSAStartup()WSACleanup()必须平衡。

  • WinSock 初始化是一个协商的过程;您有责任验证WSAStartup()返回的信息以确保它满足您的应用程序的要求。

  • 现有套接字不受后续WSAStartup()调用的影响。

  • 允许使用不同 WinSock 版本的多个套接字。

See the WSAStartup()documentationfor more information.

请参阅WSAStartup()文档以获取更多信息。