简体   繁体   English

Winsock编程

[英]Winsock Programming

I have had nothing but trouble with Winsock since I started using it. 自从我开始使用它以来,我对Winsock只有麻烦。 I cannot seem to initialize Winsock to save my life. 我似乎无法初始化Winsock来拯救我的生命。 I'm not asking for anyone to write the whole program ( As I know how annoying that is ) I just need help with Winsock. 我不是要求任何人编写整个程序(因为我知道这有多烦人)我只需要帮助Winsock。 I have tried several compilers and always get weird errors. 我已经尝试了几个编译器,总是会遇到奇怪的错误。

1>Compiling...
1>main.cpp
1>Linking...
1>main.obj : error LNK2019: unresolved external symbol __imp__WSACleanup@0 referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol __imp__WSAStartup@8 referenced in function _main
1>C:\Users\Rory\ProjectX\ProjectX\Debug\ProjectX.exe : fatal error LNK1120: 2 unresolved externals
1>Build log was saved at "file://c:\Users\Rory\ProjectX\ProjectX\ProjectX\Debug\BuildLog.htm"
1>ProjectX - 3 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Here is my code: 这是我的代码:

#include <cstdlib>
#include <iostream>
#include <string.h>
#include <winsock2.h>

int iReqWinsockVer = 2;

using namespace std;

int main()
{
    cout<<"Initializing Winsock 2...\n";

    // WINSOCK INITIALIZATION

WSADATA wsaData;

if (WSAStartup(MAKEWORD(iReqWinsockVer,0), &wsaData)==0) {
    // Check if major version is at least iReqWinsockVer
    if (LOBYTE(wsaData.wVersion) >= iReqWinsockVer) {
        // Network stuff here
    }
    else {
        // Required version not available
    }

    // Cleanup winsock
    if (WSACleanup()!=0) {
        // cleanup failed
        }
    }
else {
    //  startup failed
}
    // END WINSOCK INITIALIZATION

        system("PAUSE");
    }

Add ws2_32.lib as linker input. 添加ws2_32.lib作为链接器输入。

Project Properties->linker->input page 项目属性 - >链接器 - >输入页面

On that page you will see Additional Dependencies. 在该页面上,您将看到其他依赖项。 Put it in there - note that library names should be seperated with spaces Or you could add this line directly to your source file: 把它放在那里 - 请注意库名称应该用空格分隔或者您可以将此行直接添加到源文件中:

#pragma comment(lib, "ws2_32.lib") 

Don't forget to define the WINDOWS_LEAN_AND_MEAN macro before including the windows header. 在包含Windows标头之前,不要忘记定义WINDOWS_LEAN_AND_MEAN宏。 Otherwise you will get tons of errors. 否则你会得到很多错误。 That's because the windows header by default include the old winsock version. 那是因为默认情况下Windows标头包含旧的winsock版本。 It contains lot of stuff that collides with the new winsock2 header. 它包含许多与新的winsock2标头冲突的东西。 But by defining that macro the old winsock header is excluded. 但是通过定义该宏,旧的winsock标头被排除在外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM