1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
/*
* Portable TCP session stream functions.
* $Id$
* Copyright (c) 1997 by Tycho Softworks.
* For conditions of distribution and reuse see product license.
*/
#include <net/stream.h>
#include <std/string.h>
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;
}
|