Skip to content

Instantly share code, notes, and snippets.

@rikoudosenin
Created July 2, 2017 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rikoudosenin/9f8850744ea5b4e3895b37e9408ce36b to your computer and use it in GitHub Desktop.
Save rikoudosenin/9f8850744ea5b4e3895b37e9408ce36b to your computer and use it in GitHub Desktop.
Using winsocks
#include <WinSock2.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
int main() {
//Winsock Startup
WSAData wsaData;
WORD DllVersion = MAKEWORD(2, 1);
if(WSAStartup(DllVersion, &wsaData) != 0) //If it returns anything other than 0 that means an error occured
{
MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
exit(1);
}
SOCKADDR_IN addr; //Address that we will bind our listening socket to
int addrlen = sizeof(addr); //length of the address (required for accept call)
addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //Boradcast locally
addr.sin_port = htons(1111); //Port
addr.sin_family = AF_INET; //IPv4 Socket
SOCKET sListen = socket(AF_INET, SOCK_STREAM, 1); //Create socket to listen to new Connections
bind(sListen, (SOCKADDR*)&addr, sizeof(addr)); //Bind the address to the socket
listen(sListen, SOMAXCONN); //Places sListen socket in a state in which it is listening for an incoming connection NOTE: SOMAXCONN = Socket Outstanding Max Connections
SOCKET newConnection; //Socket to hold the client's connection
newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen); // Accept a new connection
if(newConnection == 0) //If accepting the client connection failed
{
std::cout << "Failed to accept the client's connection." << std::endl;
} else { // if the client connection is properly accepted
std::cout << "Client Connected!" << std::endl;
}
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment