//
// Connection.h
//
// (c) Copyright 1993, San Diego State University -- College of Sciences
//       (See the COPYRIGHT file for more Copyright information)
//
// This class forms a easy to use interface to the berkeley tcp socket library.
// All the calls are basically the same, but the parameters do not have any
// stray _addr or _in mixed in...
//

#if !defined(_Connection_h_)
# define	_Connection_h_

#include "xvgopher.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

class Connection
{
public:
	// Constructors & Destructors
					Connection();
					Connection(int socket);
					~Connection();

	// (De)initialization
	int				open(int priv = 0);
	int				close();

	// Port stuff
	int				assign_port(int port = 0);
	int				assign_port(char *service);
	int				get_port();
	int				is_privileged();

	// Host stuff
	int				assign_server(char *name);
	int				assign_server(dword addr = INADDR_ANY);

	// Connection establishment
	int				connect();
	Connection		*accept(int priv = 0);
	Connection		*accept_privileged();

	// Registration things
	int				bind();
	int				listen(int n = 5);

	// IO
	int				write(char *buffer, int length);
	int				write(char *buffer);
	int				read(char *buffer, int length);
	char			*read_line(char *buffer, int length);
	int				read_partial(char *buffer, int maxlength);
	int				bytes_available();
	int				get_char();

	// Access to socket number
	char			*socket_as_string();
	int				get_socket();
	int				isopen();

private:
	enum
	{
		BUFFER_SIZE = 1024,
	};
	int				sock;
	struct sockaddr_in	server;
	char			buffer[BUFFER_SIZE];
	int				pos, pos_max;
};


//*************************************************************************
// inline int Connection::is_privileged()
// PURPOSE:
//   Return whether the port is priveleged or not.
//
inline int Connection::is_privileged()
{
	return server.sin_port < 1023;
}


#endif
