Simple Winsock Program

Make sure to link this with ws2_32.lib. In Visual Studio, go to Solution Explorer, right click your project, select Properties. Go to Configuration Properties, Linker, Input. Edit Additional Dependencies to include ws2_32.lib. Click Apply then OK.

#include "winsock2.h"
#include <iostream>
using namespace std;

void wsock_init();

int main() {
    wsock_init();
    SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in si;
    si.sin_family = AF_INET;
    si.sin_port = htons(666);
    si.sin_addr = *(struct in_addr*)gethostbyname("towel.blinkenlights.nl")->h_addr;
    memset(&(si.sin_zero), 0, 8);

    if (connect(sock, (struct sockaddr*)&si, sizeof(struct sockaddr))) {
        cout << "Could not connect to host.\n";
        return 1;
    }
    
    char buf[4096];
    while (recv(sock, buf, 4096, 0)) 
        cout << buf;

    shutdown(sock, SD_BOTH);
    closesocket(sock);
    WSACleanup();

    getchar();
    return 0;
}

void wsock_init() {
    WSADATA wd;
    if (WSAStartup(MAKEWORD(1, 1), &wd)) {
        cout << "Error initializing Winsock DLL" << endl;
        exit(1);
    }
}

2 thoughts on “Simple Winsock Program

    • That is supposed to be the built-in socket library for computers running Windows. It should come bundled with any C/C++ compiler for Windows.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: