我刚刚开始通过“Beej网络编程指南”学习winsock。我正在windows下编程,并通过gcc运行它。这只是编写我的第一个服务器程序的一个开始,但是当我试图编译时,它会给我带来这些错误。
/* Server */
#include <iostream>
#include <windows.h>
#include <winsock2.h>
using namespace std;
const int winsockVersion = 2;
#define BACKLOG 10
#define PORT 3000
int main(void){
WSADATA wsadata;
if (WSAStartup(MAKEWORD(winsockVersion,0),&wsadata) == 0){
struct addrinfo hints, *res;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ( getaddrinfo(NULL,PORT,&hints,&res) == 0 ){
cout<<"-Call to get addrinfo successful!." << endl;
}
cout<<"res af_family" << res->ai_family << endl;
}
//clear stuff
if( WSACleanup() != 0){
cout<<"-WSACleanup unsuccessful" << endl;
}else{
cout<<"-WSACleanup successful" << endl;
}
return 0;
}这些是我收到的错误
g++ -o server.exe server.cpp -lws2_32
Process started >>>
server.cpp: In function `int main()':
server.cpp:20: error: aggregate `addrinfo hints' has incomplete type and cannot be defined
server.cpp:25: error: `AI_PASSIVE' was not declared in this scope
server.cpp:27: error: `getaddrinfo' was not declared in this scope
server.cpp:31: error: invalid use of undefined type `struct addrinfo'
server.cpp:20: error: forward declaration of `struct addrinfo'
server.cpp:54:2: warning: no newline at end of file
<<< Process finished.不应该在windows.h或winsock.h中定义结构和函数吗?
溶液
编辑给任何绊脚石的人,添加
#define _WIN32_WINNT 0x501
#include <ws2tcpip.h>在源的顶部,如果getaddrinfo说它未声明。
发布于 2010-11-22 07:14:30
你可能想要#include <ws2tcpip.h>。请记住,在堆栈溢出之前,谷歌是此类问题的朋友:您将立即从MSDN获得答案!
发布于 2014-07-09 10:34:21
MSDN说我们应该使用#include <ws2tcpip.h>,但是在ws2tcpip.h中我找到了这段代码:
#if (_WIN32_WINNT >= _WIN32_WINNT_WINXP)
/**
* For WIN2K the user includes wspiapi.h for these functions.
*/
void WSAAPI freeaddrinfo (struct addrinfo*);
int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
struct addrinfo**);
int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
char*,DWORD,int);
#endif /* (_WIN32_WINNT >= _WIN32_WINNT_WINXP) */这意味着,_WIN32_WINNT的定义低于_WIN32_WINNT_WINXP,但是当我尝试包含wspiapi.h时,得到了"no such file or directory"。我的猜测是,这是MinGW的一个错误,因为库的不同部分的版本不一致。你必须自己做#define _WIN32_WINNT _WIN32_WINNT_WINXP,然后才能包括ws2tcpip.h
发布于 2010-11-22 09:23:46
小心!你的包错了。问题是windows.h已经包含了winsock.h和winsock2.h,然后重新定义了一些结构和函数,导致大量编译错误。将windows.h包含移到winsock2.h包含下面,或者完全删除windows.h包含,winsock2.h包含windows.h。
https://stackoverflow.com/questions/4243027
复制相似问题