-
-
Save Benargee/983da7e6c2a635aa0a3c to your computer and use it in GitHub Desktop.
Basic Winsock Program
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 "stdafx.h" | |
#include <WinSock2.h> | |
#include <ws2tcpip.h> | |
#pragma comment(lib, "Ws2_32.lib") | |
void run_client() | |
{ | |
WSADATA wsaData; | |
WSAStartup( MAKEWORD(2,2), &wsaData ); | |
ADDRINFO hints, *result; | |
hints.ai_family = AF_UNSPEC; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_protocol = IPPROTO_TCP; | |
getaddrinfo( "127.0.0.1", "80", &hints, &result); | |
SOCKET client = socket( result->ai_family, result->ai_socktype, result->ai_protocol ); | |
connect( client, result->ai_addr, result->ai_addrlen ); | |
const char* greeting = "hello, I'm client."; | |
send( client, greeting, strlen(greeting), 0 ); | |
shutdown( ConnectSocket, SD_SEND /*SD_BOTH*/); // finish send | |
const int buff_len = 512; | |
char recv_buff[buff_len]; | |
recv( client, recv_buff, buff_len, 0); | |
closesocket(client); | |
} |
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 "stdafx.h" | |
#include <WinSock2.h> | |
#include <ws2tcpip.h> | |
#pragma comment(lib, "Ws2_32.lib") | |
void run_server() | |
{ | |
WSADATA wsaData; | |
WSAStartup( MAKEWORD(2,2), &wsaData ); | |
ADDRINFO hints, *result; | |
ZeroMemory(&hints, sizeof(ADDRINFO)); | |
hints.ai_family = AF_INET; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_protocol = IPPROTO_TCP; | |
hints.ai_flags = AI_PASSIVE; | |
getaddrinfo( nullptr, "80", &hints, &result ); | |
SOCKET listen_sock = socket( result->ai_family, result->socktype, result->ai_protocol ); | |
bind( listen_sock, result->ai_addr, (int)result->ai_addrlen ); | |
listen( listen_sock, SOMAXCONN ); | |
SOCKET client = accept( listen_sock, nullptr, nullptr ); | |
const int BUFF_LEN = 512; | |
char buff[BUFF_LEN]; | |
int recv_size = recv( client, buff, BUFF_LEN, 0 ); | |
send( client, buff, recv_size, 0 ); | |
closesocket( client ); | |
closesocket( listen_socket ); | |
WSACleanup(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment