开发者

How to create socket via socket() on MSVC?

I am porting linux app under win32 (msvc 9.0) and after finally finishing it, I'm experiencing non-default behavior on simple things as socket().

#include <winsock2.h>
#include <ws2tcpip.h>

int main(int argc, char **argv)
{
    int subsock;
    if ((subsock = socket(PF_INET, SOCK_STREAM, 0)) < 0 ) { 
        printf("Failed to open socket (ret value = %d)\n", subsock);
    }
}

This prints Failed to open socket (ret value = -1) every t开发者_JAVA技巧ime. What is wrong and how to open socket on win32?


You need to call WSAStartup to initialize winsock before subsequent socket calls will succeed.

WORD wVersionRequested;
WSADATA wsaData;
int err;

/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData)
if (err != 0)
{
    YourError!
}
else
{
    // success
}

For more details:

http://msdn.microsoft.com/en-us/library/ms742213%28VS.85%29.aspx

Just request version 2.2 and be done with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜