I am a C++ noob.
I want to use Winsock to send a HTTP request to an IP address. I found a lot of content online, which is great. All of the example had the same errors, I realized that they all require Winsock.
I never used a library in C++, I don't know what or how to link anything to my project (in Visual Studio), or what I need to download.
It specifically does not like the following lines of code
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
#include<netdb.h> //hostent
The Microsoft guide does not tell me how to fix or link the library to my project.
How do I link and use Winsock?
Thank You!
It specifically does not like the following lines of code
#include<sys/socket.h> //socket #include<arpa/inet.h> //inet_addr #include<netdb.h> //hostent
Those headers are not available on Windows, they are used on other platforms only.
How do I link and use Winsock?
On Windows, you need to use winsock.h
or winsock2.h
in your code, and link to ws2_32.lib
.
And you need to call WSAStartup()
and WSACleanup()
, which do not exist on other platforms.
And you need to use SOCKET
instead of int
for socket handles. On Windows, sockets are true kernel objects. On other platforms, they are represented as file descriptors.
And you need to call closesocket()
instead of close()
when disconnecting/freeing a socket handle.
Beyond that, most other BSD-based socket API function calls (socket()
, bind()
, connect()
, recv()
, send()
, select()
, etc) work the same in Windows as in other platforms (well, select()
has one minor difference - the first parameter is ignored). And, of course, WinSock has many Windows-specific extensions that other platforms do not have. But if you are trying to use someone else's code that you found online, chances are it is using the BSD-compatible functions only.
That being said, Winsock is a lower-level networking API and very difficult for noobs to use correctly. And then you have to add an application-layer protocol, like HTTP, on top of it, which is even harder for noobs to get right. Wanting to learn something new is great, but jumping right into HTTP without understanding the fundamentals first is a recipe for disaster. You are better off using Microsoft's WinInet or WinHTTP API instead, let it handle all of the networking and protocol details for you.