-
Notifications
You must be signed in to change notification settings - Fork 8
/
tcp.c
93 lines (83 loc) · 2.01 KB
/
tcp.c
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
89
90
91
92
93
/* TCP specific code, pulled out from supdup.c. */
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "supdup.h"
#if defined(_AIX) || defined(__sun)
#undef bcopy
#define bcopy(__src, __dst, __len) memcpy(__dst, __src, __len)
#endif
#define STANDARD_PORT 95 /*Per gospel from St. Postel.*/
static int
get_port(struct sockaddr_in *tsin, const char *port)
{
if (port == NULL) {
struct servent *sp = getservbyname ("supdup", "tcp");
if (sp == NULL)
tsin->sin_port = htons(STANDARD_PORT);
else
tsin->sin_port = sp->s_port;
} else {
if ((atoi (port) < 0) || (atoi (port) > 65535)) {
fprintf(stderr,"%s: bad port number.\n", port);
return -1;
}
tsin->sin_port = atoi (port);
if (tsin->sin_port == 0) {
fprintf(stderr,"%s: bad port number.\n", port);
return -1;
}
tsin->sin_port = htons (tsin->sin_port);
}
return 0;
}
static int
get_host (struct sockaddr_in *tsin, const char *name)
{
struct hostent *host;
host = gethostbyname (name);
if (host)
{
tsin->sin_family = host->h_addrtype;
#ifdef notdef
bcopy (host->h_addr_list[0], (void *) &tsin->sin_addr, host->h_length);
#else
bcopy (host->h_addr, (void *) &tsin->sin_addr, host->h_length);
#endif /* h_addr */
return 0;
}
else
{
tsin->sin_family = AF_INET;
tsin->sin_addr.s_addr = inet_addr (name);
if (tsin->sin_addr.s_addr == -1)
return -1;
else
return 0;
}
}
int
tcp_connect(const char *host, const char *port)
{
struct sockaddr_in tsin;
int fd;
if (get_port(&tsin, port) < 0 || get_host(&tsin, host) < 0)
return -1;
fd = socket (AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
perror ("supdup: socket");
return -1;
}
if (connect (fd, (struct sockaddr *) &tsin, sizeof (tsin)) < 0) {
close(fd);
perror ("supdup: connect");
return -1;
}
return fd;
}