-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmodem_send.c
110 lines (96 loc) · 2.02 KB
/
modem_send.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#define MODEM "tiny9300"
#define PORT 3105
#define BUF_SIZE 4096
static char buf[BUF_SIZE];
int main(int argc, char *argv[])
{
struct addrinfo hints, *res;
struct sockaddr_in addr;
int rsock, wsock;
int len;
int n;
FILE *fp = stdin;
int err;
int pid;
int status;
char *modem;
switch (argc) {
case 1:
modem = MODEM;
break;
case 2:
modem = argv[1];
break;
default:
fprintf(stderr, "usage: modem_send [host]\n");
exit(1);
}
bzero(&hints, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
err = getaddrinfo(modem, NULL, &hints, &res);
if (err != 0) {
fprintf(stderr, "getaddrinfo error: %d\n", err);
exit(1);
}
addr.sin_addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
wsock = socket(AF_INET, SOCK_STREAM, 0);
if (wsock < 0) {
perror("socket");
exit(1);
}
if (connect(wsock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("connect");
exit(1);
}
#if 0
rsock = socket(AF_INET, SOCK_STREAM, 0);
if (rsock < 0) {
perror("socket");
exit(1);
}
if (connect(rsock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("connect");
exit(1);
}
#else
rsock = wsock;
#endif
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
/* write data to modem */
while ((len = fread(buf, 1, BUF_SIZE, fp)) > 0) {
n = write(wsock, buf, len);
if (n != len) {
fprintf(stderr, "write modem error: %d\n", n);
break;
}
}
fclose(fp);
shutdown(wsock, 1); // close write side
exit(0);
}
/* read dat from modem */
while ((len = read(rsock, buf, BUF_SIZE)) > 0) {
n = fwrite(buf, 1, len, stdout);
if (n != len) break;
}
if (wait(&status) < 0) {
perror("wait");
}
close(rsock);
return 0;
}