Created
July 2, 2017 15:16
-
-
Save rikoudosenin/9f8850744ea5b4e3895b37e9408ce36b to your computer and use it in GitHub Desktop.
Using winsocks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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