So I am trying to implement a basic server in C++, I am using code blocks with minGW, when I go to run build the server I get a series of errors
undefined reference to `__imp_socket' undefined reference to `__imp_WSAStartup' undefined reference to `__imp_bind' undefined reference to `__imp_listen' undefined reference to `__imp_accept'
etc. basically all the networking functions used in the code below I believe the issue is with linking which was what the #pragma comment (lib, "ws2_32.lib") was supposed to solve. I have also tried compiling with g++ main.cpp -lws2_32 and g++ main.cpp -o main -lws2_32 to no avail. 99% sure the issue is not with the code but I included it below anyway. Hoping someone has another suggestion
#include <iostream>
#include <ws2tcpip.h>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
int main()
{
//initialize winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOK = WSAStartup(ver, &wsData);
if(wsOK != 0){
cerr << "Can't initialize winsock" << endl;
return -1;
}
// create a socket & bind to an ip and port
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if(listening == INVALID_SOCKET){
cerr << "Can't create a socket" << endl;
return -1;
}
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.S_un.S_addr = INADDR_ANY;
bind(listening, (sockaddr*)&hint, sizeof(hint));
// Tell winsock to listen
listen(listening, SOMAXCONN);
// wait for connection
sockaddr_in client;
int clientsize = sizeof(client);
SOCKET clientsocket = accept(listening, (sockaddr*)&client, &clientsize);
//if (clientsocket == INVALID_SOCKET)
char host[NI_MAXHOST]; //client remote name
char service[NI_MAXHOST]; //service port client connects on
ZeroMemory(host, NI_MAXHOST);
ZeroMemory(service, NI_MAXHOST);
if(getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0 ) == 0){
cout << host << " connected on port " << service << endl;
}
/*
else{
inet_ntoa(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << " connected on port " << ntohs(client.sin_port) << endl;
}
*/
// closet listener
//closesocket(listening);
// while loop: accept and echo message back to client
char buf[4096];
while(true){
ZeroMemory(buf, 4096);
//wait for data
int bytesRecieved = recv(clientsocket, buf, 4096, 0);
if (bytesRecieved == SOCKET_ERROR){
cerr << "Error in recv" << endl;
return -1;
}
if (bytesRecieved == 0){
cout << "client disconnected" << endl;
break;
}
//echo message back to client
send(clientsocket, buf, bytesRecieved+1, 0);
}
// close socket
closesocket(clientsocket);
// shutdown winsock
WSACleanup();
return 0;
}