开发者

How to create socket via socket() on MSVC?

开发者 https://www.devze.com 2023-02-19 23:07 出处:网络
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().

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

精彩评论

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

关注公众号