Skip to content

Instantly share code, notes, and snippets.

@whoo24
Created June 24, 2013 07:15
Show Gist options
  • Save whoo24/5848260 to your computer and use it in GitHub Desktop.
Save whoo24/5848260 to your computer and use it in GitHub Desktop.
Basic Winsock Program
#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);
}
#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();
}
@whoo24
Copy link
Author

whoo24 commented Jul 31, 2018

@kaecy I saw the code right now.
Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment