gpt4 book ai didi

c++ - winsock编译错误,找不到addrinfo结构和一些相关函数

转载 作者:IT老高 更新时间:2023-10-28 22:22:00 26 4
gpt4 key购买 nike

我刚开始通过“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 说它未声明,则在源代码的顶部。

最佳答案

您可能想要#include <ws2tcpip.h> .请记住,在 Stack Overflow 之前,Google是您这类问题的 friend 吗:您将立即从 MSDN 获得答案!

关于c++ - winsock编译错误,找不到addrinfo结构和一些相关函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4243027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com