如何使用Winsock 2?

时间:2009-08-24 11:03:14

标签: c++ file header winsock

如何在Visual Studio 2008中使用Windows套接字2.我使用预编译的标头,到目前为止我尝试的是:

  1. StdAfx.h 文件中包含 winsock2.h
  2. 并输入 WS2_32.LIB 作为项目设置中的附加依赖项
  3. 我收到这些错误

    ------ Build started: Project: TestIVR, Configuration: Debug Win32 ------
    Compiling...
    main.cpp
    c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(30) : error C2065: 'WSAEVENT' : undeclared identifier
    c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(30) : error C2146: syntax error : missing ';' before identifier 'socketEvent'
    c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(30) : error C2065: 'socketEvent' : undeclared identifier
    c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(35) : error C2039: 'S_addr' : is not a member of 'in_addr'
            c:\program files\microsoft sdks\windows\v6.0a\include\inaddr.h(22) : see declaration of 'in_addr'
    c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(40) : error C2065: 'socketEvent' : undeclared identifier
    c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(40) : error C3861: 'WSAEventSelect': identifier not found
    Build log was saved at "file://c:\Documents and Settings\Hussain\My Documents\Visual Studio 2008\Projects\TestIVR\TestIVR\Debug\BuildLog.htm"
    TestIVR - 6 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    

    顺便说一句,如果我在 main.cpp (我的main()函数所在的位置)中包含 winsock2.h ,那么我会得到不同的错误

    ------ Build started: Project: TestIVR, Configuration: Debug Win32 ------
    Compiling...
    main.cpp
    c:\documents and settings\hussain\my documents\visual studio 2008\projects\testivr\testivr\main.cpp(36) : error C2039: 'S_addr' : is not a member of 'in_addr'
            c:\program files\microsoft sdks\windows\v6.0a\include\inaddr.h(22) : see declaration of 'in_addr'
    Build log was saved at "file://c:\Documents and Settings\Hussain\My Documents\Visual Studio 2008\Projects\TestIVR\TestIVR\Debug\BuildLog.htm"
    TestIVR - 1 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    

    以下是 StdAfx.h 标题文件的内容

    #pragma once
    
    #include <stdio.h>
    #include <tchar.h>
    #include <windows.h>
    #include <winsock2.h>
    

4 个答案:

答案 0 :(得分:5)

你的in_addr问题是由于事实上in_addr中没有S_addr字段引起的。有一个in_addr.s_addr可以重定向到in_addr.S_un.S_addr。

答案 1 :(得分:4)

从内存中我认为windows.h包含winsock.h(即套接字v1),它与winsock2.h冲突。您可以通过定义WIN32_LEAN_AND_MEAN

来防止这种情况发生
#include <stdio.h>
#include <tchar.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>

答案 2 :(得分:3)

您需要在windows.h之前包含winsock2.h

答案 3 :(得分:0)

尝试浏览

http://www.sockets.com/示例