2 listen on a TCP port. When a connection comes in, open a local character devices
3 (such as a serial port) and send/recv data between the tcp socket and the serial
6 tridge@samba.org, March 2004
17 #include <sys/socket.h>
23 #include <sys/ioctl.h>
24 #include <sys/types.h>
26 #include <arpa/inet.h>
27 #include <netinet/in.h>
29 static void set_nonblocking(int fd)
31 unsigned v = fcntl(fd, F_GETFL, 0);
32 fcntl(fd, F_SETFL, v | O_NONBLOCK);
36 open a socket of the specified type, port and address for incoming data
38 static int open_socket_in(int port)
40 struct sockaddr_in sock;
44 memset(&sock,0,sizeof(sock));
46 #ifdef HAVE_SOCK_SIN_LEN
47 sock.sin_len = sizeof(sock);
49 sock.sin_port = htons(port);
50 sock.sin_family = AF_INET;
52 res = socket(AF_INET, SOCK_STREAM, 0);
54 fprintf(stderr, "socket failed\n"); return -1;
58 setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
60 if (bind(res, (struct sockaddr *)&sock, sizeof(sock)) < 0) {
67 /* write to a file descriptor, making sure we get all the data out or
69 static void write_all(int fd, unsigned char *s, size_t n)
82 #define MAX(a,b) ((a)>(b)?(a):(b))
84 static void main_loop(int fd1, int fd2)
86 unsigned char buf[1024];
99 ret = select(MAX(fd1, fd2)+1, &fds, NULL, NULL, NULL);
100 if (ret == -1 && errno == EINTR) continue;
103 if (FD_ISSET(fd1, &fds)) {
104 int n = read(fd1, buf, sizeof(buf));
106 write_all(fd2, buf, n);
109 if (FD_ISSET(fd2, &fds)) {
110 int n = read(fd2, buf, sizeof(buf));
112 write_all(fd1, buf, n);
118 static int open_serial(const char *device)
124 fd = open(device, O_RDWR);
129 asprintf(&cmd, "stty 5:4:cbe:a30:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0 < %s", device);
133 if (ioctl(fd,TCGETS,&tty) != 0) {
138 tty.c_cflag &= ~CBAUD;
139 tty.c_cflag |= B19200;
141 if (ioctl(fd,TCSETS,&tty) != 0) {
149 int main(int argc, char *argv[])
155 struct sockaddr addr;
156 int in_addrlen = sizeof(addr);
160 printf("Usage: serialtcp <inport> <device>\n");
164 listen_port = atoi(argv[1]);
167 signal(SIGCHLD, SIG_IGN);
169 listen_fd = open_socket_in(listen_port);
171 if (listen_fd == -1) {
172 fprintf(stderr,"listen on port %d failed - %s\n",
173 listen_port, strerror(errno));
177 if (listen(listen_fd, 5) == -1) {
178 fprintf(stderr,"listen failed\n");
182 while ((sock_in = accept(listen_fd,&addr,&in_addrlen)) != -1) {
186 fd_out = open_serial(device);
193 main_loop(sock_in, fd_out);