#include <sys/types.h>
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>

char *readline()
{
    static char rtn[132];
    int  i = 0;
    char the_char = fgetc(stdin);

    while(the_char != '\n')
    {
        rtn[i] = the_char;
        i++;
        if (i > 130) break;
        the_char = fgetc(stdin);
        if (the_char == '\r')
            the_char = fgetc(stdin);
        if (feof(stdin)) break;
    }
    rtn[i] = '\0';

    return rtn;
}

int main()
{
    WSADATA WSAData;
    SOCKET sock;
    struct sockaddr_in sa;
    int iErr;
    char rec_buf[1024];
    char send_buf[132];
    int msg_size;

    iErr = WSAStartup(MAKEWORD(2,0), &WSAData);
    if (iErr)
    {
        char err_msg_buf[240];
        strerror_s(err_msg_buf, 240, iErr);
        printf("Error calling WSAStartup, %s\n", err_msg_buf);
    }
    sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET)
    {
        char err_msg_buf[240];
        strerror_s(err_msg_buf, 240, WSAGetLastError());
        printf("Socket creation error %s\n", err_msg_buf);
        WSACleanup();
        exit(-1);
    }

    sa.sin_family = AF_INET;
    sa.sin_port   = htons(51324);
    sa.sin_addr.S_un.S_addr = inet_addr("166.18.10.36");

    iErr = connect(sock, (SOCKADDR *)&sa, sizeof(sa));
    printf("connect returned %d\n", iErr);
    // Silly windows.
    if (iErr == SOCKET_ERROR)
    {
        char err_msg_buf[240];
        strerror_s(err_msg_buf, 240, WSAGetLastError());
        printf("Connect error %s\n", err_msg_buf);
        WSACleanup();
        exit(-1);
    }

    while (1)
    {
        printf("Enter a string -> ");
        fflush(NULL);
        strcpy(send_buf, readline());
        if (strlen(send_buf) == 0) break;
        send(sock, send_buf, (int)strlen(send_buf)+1, 0);
        msg_size = recv(sock, rec_buf, 1023, 0);
        if (msg_size == 0)
        {
            printf("Socket unexpectedly closed by server\n");
            break;
        }
        rec_buf[msg_size] = '\0';
        printf("Recieved: %s\n", rec_buf);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
}

This page last updated on 7/15/08

Return to Sockets page

Return to programming notes page