/* * Portable TCP session stream functions. * $Id$ * Copyright (c) 1997 by Tycho Softworks. * For conditions of distribution and reuse see product license. */ #include #include STREAM opentcp(const char *host, int port) { SOCKET so = getsocket(host, port, SOCK_STREAM); FILE *fp; if(so == INVALID_SOCKET) return NULL; fp = fdopen(so, "r+"); if(!fp) { endsocket(so); return NULL; } buftcp(fp, 0); return fp; } char *gettcp(char *buf, size_t count, STREAM fp) { memset(buf, 0, count); if(!fgets(buf, count, fp)) return NULL; return buf; } int puttcp(char *buf, STREAM fp) { int err; err = fputs(buf, fp); fflush(fp); return err; } void closetcp(STREAM fp) { SOCKET so = fileno(fp); fflush(fp); shutdown(so, 2); fclose(fp); } int buftcp(STREAM fp, int size) { fflush(fp); if(!size) return setvbuf(fp, NULL, _IOLBF, 1024); else return setvbuf(fp, NULL, _IOFBF, size); } STREAM accepttcp(SOCKET so) { struct sockaddr addr; int len; int si; FILE *fp; len = sizeof(addr); si = accept(so, &addr, &len); if(si < 0) return NULL; fp = fdopen(si, "r+"); if(!fp) { shutdown(si, 2); close(si); return NULL; } buftcp(fp, 0); return fp; }