/* Demonstrates the channel functions.  This example is
 * a lot like one found in the Libnet package.  */

#include <stdio.h>
#include <string.h>
#include <libnet.h>

/* Use the driver of your choice.
 * e.g. NET_DRIVER_WSOCK_WIN under Windows.  */
#define DRIVER	NET_DRIVER_SOCKETS

int main (int argc, char *argv[])
{
    NET_CHANNEL *chan;
    char *binding;
    int server = 0;
    char buf[256];
    
    /* Search command-line arguments for a "-s" option.  If 
     * found then we will run as the server, otherwise as the
     * client.  (Not that it makes much difference here).  */
    for (argv++; *argv; argv++)
	if (strcmp (*argv, "-s") == 0)
	    server = 1;

    net_init ();
    net_loadconfig (NULL);
    
    net_detectdrivers (net_drivers_all);
    net_initdrivers (net_drivers_all);

    /* If we are the server we want to have the "default"
     * address (i.e. binding should be the empty string).
     * If we are the client, our address doesn't matter
     * (i.e. the binding should be NULL).  */
    if (server)
	binding = "";
    else
	binding = NULL;

    /* Open the channel.  */
    chan = net_openchannel (DRIVER, binding);
    if (!chan) {
	puts ("Error opening channel.");
	return 1;
    }

    /* Show the local address.  */
    printf ("Local address: %s\n", net_getlocaladdress (chan));

    /* Assign a target.  */
    puts ("Enter target address:");
    fgets (buf, sizeof buf, stdin);
    if (net_assigntarget (chan, buf) != 0) {
	puts ("Could not use that address; quitting.");
	return 1;
    }
    
    puts ("Enter text to send.  Enter `.' to quit.");
    
    while (1) {
	/* Check if the remote side sent us any messages.  */
	while (net_query (chan))
	    /* If so, receive them and print them out.  */
	    if (net_receive (chan, buf, sizeof buf, NULL) > 0)
		printf ("Received: %s\n", buf);

	/* Let user enter something.  */
	if (!fgets (buf, sizeof buf, stdin))
	    break;
	buf[strlen (buf) - 1] = 0;   /* strip newline */

	/* Quit condition.  */
	if (strcmp (buf, ".") == 0)
	    break;

	/* Send the text if it is not a blank line.  */
	if (buf[0])
	    net_send (chan, buf, strlen (buf) + 1);
    }

    /* Close the channel.  */
    net_closechannel (chan);

    /* Quit.  */
    return 0;
}

