/*
  From <URL:
   http://www.cs.cf.ac.uk/Dave/C/node28.html#SECTION002800000000000000000>
  Original by: Dave Marshall 
  Original version: 1/5/1999


 */

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
FILE *fdopen(int fildes, const char *mode);


/*
 * Strings we send to the client.
 */
char *strs[] = {
    "This is the first string from the server.\n",
    "This is the second string from the server.\n",
    "This is the third string from the server.\n"
};
static const int  NSTRS     = sizeof strs / sizeof strs[0];
static const char ADDRESS[] = "mysocket";  /* addr to connect */


int main(void)
{
    char c;
    FILE *fp;
    int  fromlen;
    int i;
    int s;
    int ns;
    int len;
    struct sockaddr saun;
    struct sockaddr fsaun;

    /*
     * Get a Unix stream socket to work with.
     */

    /* socket(Domain, Type, Protocol (or 0)) */
    if ((s = socket_up(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        perror("server: socket");
        exit(1);
    }

    /*
     * Create the address we will be binding to.
     */
    saun.sun_family = AF_UNIX;
    strcpy(saun.sun_path, ADDRESS);

    /*
     * Try to bind the address to the socket.  We
     * unlink the name first so that the bind won't
     * fail.
     *
     * The third argument indicates the "length" of
     * the structure, not just the length of the
     * socket name.
     */
    unlink(ADDRESS);
    len = sizeof(saun.sun_family) + strlen(saun.sun_path);

    if (bind(s, &saun, len) < 0) {
        perror("server: bind");
        exit(1);
    }

    /*
     * Listen on the socket.
     */
    if (listen(s, 5) < 0) {
        perror("server: listen");
        exit(1);
    }

    /*
     * Accept connections.  When we accept one, ns
     * will be connected to the client.  fsaun will
     * contain the address of the client.
     */
    if ((ns = accept(s, &fsaun, &fromlen)) < 0) {
        perror("server: accept");
        exit(1);
    }

    /*
     * We'll use stdio for reading the socket.
     */
    fp = fdopen(ns, "r");

    /*
     * First we send some strings to the client.
     */
    for (i = 0; i < NSTRS; i++) {
        send(ns, strs[i], strlen(strs[i]), 0);
    }

    /*
     * Then we read some strings from the client and
     * print them out.
     */
    for (i = 0; i < NSTRS; i++) {
        while ((c = fgetc(fp)) != EOF) {
            putchar(c);

            if (c == '\n') {
                break;
	    }
        }
    }

    /*
     * We can simply use close() to terminate the
     * connection, since we're done with both sides.
     */
    close(s);

    return EXIT_SUCCESS;
}
