-2

I am trying to compile following socket server in windows making use of the library winsock2.h. in clion v3.8

#include <iostream>
#include <winsock2.h>

using namespace std;

int main()
{
WSADATA WSAData;

SOCKET server, client;

SOCKADDR_IN serverAddr, clientAddr;

WSAStartup(MAKEWORD(2,0), &WSAData);
server = socket(AF_INET, SOCK_STREAM, 0);

serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(5555);

bind(server, (SOCKADDR *)&serverAddr, sizeof(serverAddr));
listen(server, 0);

cout << "Listening for incoming connections..." << endl;

char buffer[1024];
int clientAddrSize = sizeof(clientAddr);
if((client = accept(server, (SOCKADDR *)&clientAddr, &clientAddrSize)) != INVALID_SOCKET)
{
    cout << "Client connected!" << endl;
    recv(client, buffer, sizeof(buffer), 0);
    cout << "Client says: " << buffer << endl;
    memset(buffer, 0, sizeof(buffer));

    closesocket(client);
    cout << "Client disconnected." << endl;
}
}

I get the following error for every function from the Winsock2 library same as

CMakeFiles\projectServer.dir/objects.a(main.cpp.obj): In function `main':
C:/Users/yilmaz/CLionProjects/projectServer/main.cpp:17: undefined reference to `WSAStartup@8'
C:/Users/yilmaz/CLionProjects/projectServer/main.cpp:18: undefined reference to `socket@12'
C:/Users/yilmaz/CLionProjects/projectServer/main.cpp:22: undefined reference to `htons@4'
.......

I've been looking for googe too many times, but I have not found what is compatible with clion.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
Yılmaz edis
  • 146
  • 3
  • 13
  • You need to link your application with the library. ["The lib file of winsock is "ws_32.lib" (or "ws2_32.lib"), please make sure you've added it."](https://stackoverflow.com/questions/9249886/how-to-link-winsock-lib) – uta Mar 10 '18 at 10:35
  • i couldn't find linker setting in clion. I think some people are eager to down vote. i found those solution which are not solved my problem – Yılmaz edis Mar 10 '18 at 11:15
  • 1
    It is not CLion linker options. That is CMake linker options. Please, read https://cmake.org/cmake/help/v3.9/command/target_link_libraries.html – uta Mar 11 '18 at 15:23
  • Thank you uta. I understand. And my code is running – Yılmaz edis Mar 11 '18 at 15:28

1 Answers1

2

Requirements

+---------+------------+
| Library | Ws2_32.lib |
+---------+------------+

Add Ws2_32.lib to linking libraries in the linker settings.

273K
  • 29,503
  • 10
  • 41
  • 64