I am trying to write a simple socket code in codelite on windows but I can not import ws2_32.h so my project is not working and I am getting "No such file or directory".How can i fix this problem.I tried to write this in the linker options but I could not be successful.I researched the problems like this but I could not understand.This is a new version of Codelite and different from others.I am using MinGW as compiler.
Edit: I removed the library which one unnecessary and wrong(#include "ws2_32.h") and when I add "-Iws2_32" to the linker options problem solved.
#define _WINSOCK_DEPRECATED_NO_WARNINGS
//#ifndef WIN32_LEAN_AND_MEAN
//#define WIN32_LEAN_AND_MEAN
//#endif
#include <stdio.h>
#include <string.h>
#include "winsock2.h"
#include "ws2_32.h"
#include <WS2tcpip.h>
#define SERVER_BUF 10
#define SAME 0
#define G_BUF 1024
int main()
{
WSADATA wsa=NULL;
SOCKET s, new_socket;
char buf[SERVER_BUF];
char gbuf[G_BUF];
struct sockaddr_in server_information;
struct sockaddr_in client_information;
WSAStartup(MAKEWORD(2, 2), &wsa);
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
printf("Initialised.\n");
server_information.sin_family = AF_INET;
server_information.sin_addr.s_addr = inet_addr("192.168.10.16");
server_information.sin_port = htons(8888);
s = socket(AF_INET, SOCK_STREAM, 0);
if (s != -1)
{
printf("Soket created...");
}
if (bind(s, (struct sockaddr*)&server_information, sizeof(server_information)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d", WSAGetLastError());
}
puts("Bind done");
while (s != 0) {
if (listen(s, 1) != -1)
{
printf("Listening is successful.");
}
socklen_t size = sizeof(client_information);
new_socket = accept(s, (struct sockaddr*)&client_information, &size);
if (new_socket == -1)
{
printf("Accept failed");
return -2;
}
else
puts("Connection accepted");
for (;;) {
int res = recv(new_socket, buf, SERVER_BUF, 0);
printf("amount of bytes received:%d\n", res);
puts(buf);
fgets(gbuf, G_BUF, stdin);
send(new_socket, gbuf,strlen(gbuf)+1, 0);
if (strcmp(buf, "exit") == SAME)
break;
}
}
return 0;
}
The ws2_32
library is indeed necessary for socket functionality on Windows.
So you must link with the -lws2_32
flag.
But the include line should be #include <winsock2.h>
, and - depending on which functions you call - possibly others like #include <ws2tcpip.h>
.
Note that as these libraries are considered system include files on Windows you should use angle brackets (<>
) instead of double quotes (""
).