I've just started learning winsock through the "Beej's guide to network programming" book. I'm programming under windows and running it through gcc. This is just a start to writing my first server program but it gives me these errors when I try to compile.
/* 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;
}
these are the errors I'm receiving
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.
Shouldn't the structures and functions be defined in either windows.h or winsock.h?.
SOLUTION
EDIT to anyone who stumbles on this, add
#define _WIN32_WINNT 0x501
#include <ws2tcpip.h>
at the top of your source if getaddrinfo says that its undeclared.
You probably want to #include <ws2tcpip.h>
. Remember that before Stack Overflow, Google is your friend for this kind of questions : you will get immediate answers from MSDN !
MSDN says we should #include <ws2tcpip.h>
, but in ws2tcpip.h
i found this piece of code:
#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) */
this means, that _WIN32_WINNT
is defined lower than _WIN32_WINNT_WINXP
, but when i tried include wspiapi.h
, i got "no such file or directory"
. My guess is, this is an fault of MinGW, where different parts of the library have inconsistent versions.
You have to #define _WIN32_WINNT _WIN32_WINNT_WINXP
on your own, before including ws2tcpip.h
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With