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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
|
/*
a simple TCP connector
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "stty.h"
#define PORT 5800
#define BUFF_SIZE 4096
extern int errno;
#define max(x,y) ((x) > (y) ? (x) : (y))
void errorf (char *fmt, ...)
{
va_list args;
va_start (args, fmt);
vfprintf (stderr, fmt, args);
exit (1);
}
int main (int argc, char **argv)
{
fd_set readset;
struct sockaddr_in my_addr;
struct hostent *host;
int sock, n, fd, fdmax, port = PORT, quit = 0;
char buff[BUFF_SIZE], device[128], *s;
*device = 0;
for (n = 1; *argv[n] == '-'; n++)
switch (argv[n][1])
{
case 'd' :
strcpy (device, argv[n][2] ? &argv[n][2] : argv[++n]);
break;
case 'p' :
port = argv[n][2] ? atoi(argv[n] + 2) : atoi(argv[++n]);
break;
case 'h' :
errorf ("Usage: tcpconn [-d pty] [-p port] hostname[:port]\n");
}
if ((s = strtok(argv[n], ":")) == NULL)
errorf ("invalid hostname\n");
host = gethostbyname(s);
if ((s = strtok(NULL, ":")) != NULL)
port = atoi(s);
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
errorf ("can't create client socket (%s)\n", strerror(errno));
bzero (&my_addr, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_addr = *(struct in_addr *) host->h_addr_list[0];
my_addr.sin_port = htons(port);
if (connect(sock, (struct sockaddr *) &my_addr, sizeof(my_addr)) < 0)
errorf ("can't connect to server (%s)\n", strerror(errno));
if (*device)
{
if ((fd = open(device, O_RDWR)) < 0)
errorf ("can't open device %s (%s)", device, strerror(errno));
dup2 (fd, STDIN_FILENO);
dup2 (fd, STDOUT_FILENO);
}
else if (isatty(STDIN_FILENO))
{
stty_initstore ();
stty_raw (STDIN_FILENO);
atexit (stty_orig);
}
fdmax = max(STDIN_FILENO, sock);
while (!quit)
{
FD_ZERO (&readset);
FD_SET (STDIN_FILENO, &readset);
FD_SET (sock, &readset);
if (select(fdmax + 1, &readset, NULL, NULL, NULL) < 0)
errorf ("select failed (%s)\n", strerror(errno));
if (FD_ISSET(STDIN_FILENO, &readset))
{
if ((n = read(STDIN_FILENO, buff, BUFF_SIZE)) <= 0)
quit = 1;
else
write (sock, buff, n);
}
if (FD_ISSET(sock, &readset))
{
if ((n = read(sock, buff, BUFF_SIZE)) <= 0)
quit = 1;
else
write (STDOUT_FILENO, buff, n);
}
}
close (sock);
printf ("\r\n");
return (0);
}
|