A Tiny (Windows) Sockets Client

© Copyright 1997 University of New Haven

 
#ifndef unix
#define WIN32
#include <windows.h>
#include <winsock.h>
#else
#define closesocket close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
 
#include <stdio.h>
#include <string.h>
 
main()
{
#ifdef _MSC_VER
#define MSVCFAR far
#else
#define MSVCFAR
#endif
 
        struct  hostent  MSVCFAR *serverip;  /* pointer to a host table entry       */
        struct  sockaddr_in server;          /* structure to hold an IP address     */
        int     sd;              /* socket descriptor                   */
        char    buf[1000];       /* buffer for data from the server     */
        int     n;
 
#ifdef WIN32
        WSADATA wsaData;
        WSAStartup(0x0101, &wsaData);
#endif
 
 
        memset((char *)&server,0,sizeof(server)); /* clear sockaddr structure */
        server.sin_family = AF_INET;              /* set family to Internet     */
 
        /* Convert host name to equivalent IP address and copy to sockaddr. */
 
        serverip = gethostbyname("charger.newhaven.edu");
 
        /* or when connecting to a computer identified by IP number: */
        /* {                                                         */
        /*   long ipaddr = inet_addr("204.60.72.11");                */
        /*   serverip = gethostbyaddr(&ipaddr, 4, PF_INET);          */
        /* }                                                         */
 
        if ( !serverip ) {
                fprintf(stderr,"invalid host\n");
                exit(1);
        }
 
#ifdef _MSC_VER
        _fmemcpy(&server.sin_addr, serverip->h_addr, serverip->h_length);
#else
        memcpy(&server.sin_addr, serverip->h_addr, serverip->h_length);
#endif        
 
#define DAYTIMEPORT 13
        server.sin_port= htons(DAYTIMEPORT);
 
        /* Create a socket. */
 
        sd = socket(PF_INET, SOCK_STREAM, 0);
        if (sd < 0) {
                fprintf(stderr, "socket creation failed\n");
                exit(1);
        }
 
 
        /* Connect the socket to the specified server. */
 
        if (connect(sd, (struct sockaddr *)&server, sizeof(server)) < 0) {
                fprintf(stderr,"connect failed\n");
                exit(1);
        }
 
        /* Repeatedly read data from socket and write to user's screen. */
 
        n = recv(sd, buf, sizeof(buf), 0);
        while (n > 0) {
                write(1,buf,n);
                n = recv(sd, buf, sizeof(buf), 0);
        }
 
        /* Close the socket. */
 
        closesocket(sd);
 
        /* Terminate the client program gracefully. */
 
#ifdef WIN32
        WSACleanup();
#endif
        exit(0);
}

Home