A Tiny (Windows) Sockets Server

© 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  sockaddr_in server;          /* structure to hold an IP address     */
        int     sd, sdclient;                /* socket descriptor                   */
        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     */
        server.sin_addr.s_addr= htonl(INADDR_ANY);
#define PORT 6996
        server.sin_port= htons(PORT);
 
        /* 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 (bind(sd, (struct sockaddr *)&server, sizeof(server)) < 0) {
                fprintf(stderr,"bind failed\n");
                exit(1);
        }
 
#define QLEN 5
        if  (listen(sd, QLEN))
        {
                fprintf(stderr,"listen failed\n");
                exit(1);
        }
             
 
        for  (;;)
        {
             if  ((sdclient= accept(sd, 0, 0)) < 0) {
                fprintf(stderr,"accept failed\n");
                exit(1);
             }
 
 
             send(sdclient, "Server says hi!\n", 16, 0);
             closesocket(sdclient);
        }
 
        /* Close the socket. */
 
        closesocket(sd);
 
        /* Terminate the server program gracefully. */
 
#ifdef WIN32
        WSACleanup();
#endif
        exit(0);
}

Home