/* SockAPI.h -- Cross platform socket library William Garrison a.k.a. Moby Disk
-- Unfinished: 05/98 mobydisk@home.com
Copyright (C) 1998 William Garrison
This program is free software; you can redistribute it and/or modify it under the terms of
the GNU General Public License as published by the Free Software Foundation; either version
2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
*/
#ifndef ________SockAPI_h
#define ________SockAPI_h
#ifdef WIN32
#include <winsock.h> // Windows socket headers/definitions
#else
#include <unistd.h> // Unix socket headers/definitions
#include <netdb.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
typedef int SOCKET;
#define closesocket(x) close(x)
#endif
#include <stdio.h>
#include <iostream.h>
#define OVERRIDE_SOCKET_BUFFER
#define SOCKET_BUFSIZE 1024
class Socket : public streambuf {
protected:
SOCKET sock; // low level SOCKET
sockaddr_in remote, // Remote address structure
local; // Local address structure
char _back[2]; // Small buffer for stream handling
BOOL connected; // Flag indicating valid connection
public:
// Static initializers for the Socket library
static void init();
static void done();
// Constructors
Socket(Socket ©); // Copy constructor(yes, this is needed)
Socket();
Socket(SOCKET sock, BOOL connFlag, int); // Create a Socket from a SOCKET
Socket(const char *hostname, int port); // Create and connect to host by name
Socket(long hostaddr, int port); // Create and connect to host by address
Socket(int port); // Create and begin serving on port
~Socket(); // Shutdown, disconnect, disappear
// Connection functions
int connect(const char *hostname, int port); // Connect to host by name
int connect(long hostaddr, int port); // Connect to host by address
int listen(int backlog = SOMAXCONN); // Server listen
Socket *accept(); // Server blocking accept
void close(); // Close connection to client(not shutdown)
// Useful stuff
int peerPort(); // Various useful pieces of information
long peerAddr();
char * peerAddrStr();
char * peerName();
static char *localName(); // Get local host name
static char *dotName(long addr);
int isConnected() { return connected; }
// Streaming functions: I have no clue how this works...
int sync();
int overflow(int ch = EOF);
int underflow();
// Only use this if you want a larger buffer
#ifdef OVERRIDE_STREAM_BUFSIZER
protected:
virtual int doallocate() { char *tptr = new char[SOCKET_BUFSIZE]; setb(tptr,tptr+SOCKET_BUFSIZE,1); return 1; }
#endif
};
#endif