#include #include #include #include #include "easysock.h" #define PROG_NAME "basicproxy" #define PROG_VER "0.01" void forward_data(int from_fd, int to_fd) { int n = 0; char* buffer = malloc(3000*sizeof(char)); while ((n = recv(from_fd, buffer, 3000, 0)) > 0) { // read data from input socket send(to_fd, buffer, n, 0); // send data to output socket } } void print_prog_info() { printf("%s [Local IP address] [local port] [remote IP address] [remote port]\n",PROG_NAME); } void print_version_info() { printf("%s %s\n",PROG_NAME,PROG_VER); } void print_help_info() { printf("\n%s - A simple TCP proxy written in C.\n\n",PROG_NAME); printf("Syntax - "); print_prog_info(); printf("[Local IP address] - The local address to bind to\n" "[local port] - The local port to listen on\n" "[remote IP address] - The remote IP to connect to\n" "[remote port] - The remote port to connect to\n"); printf("\nExample: %s 127.0.0.1 3000 1.2.3.4 5000 - Listen on '127.0.0.1:3000', and forward all data from there to '1.2.3.4:5000'\n\n",PROG_NAME); } int main(int argc,char* argv[]) { /* argv[1] = local address argv[2] = local port argv[3] = remote address argv[4] = remote port */ if (argc == 2) { if (strcmp(argv[1],"-v") == 0 || strcmp(argv[1],"--version") == 0) { print_version_info(); exit(0); } else if (strcmp(argv[1],"-h") == 0 || strcmp(argv[1],"--help") == 0) { print_help_info(); exit(0); } } if (argc != 5) { print_prog_info(); exit(230); } char* local_addr = argv[1]; int local_port = strtol(argv[2],NULL,10); char* remote_addr = argv[3]; int remote_port = strtol(argv[4],NULL,10); int preferred_local_network = check_ip_ver(local_addr); int preferred_remote_network = check_ip_ver(remote_addr); printf("Using %d for local\nUsing %d for remote\n",preferred_local_network,preferred_remote_network); if ((preferred_local_network == -1) || (preferred_remote_network == -1)) { exit(207); } char preferred_transport = 'T'; struct sockaddr addr_struct; int server_sock = create_local(preferred_local_network,preferred_transport,local_addr,local_port,&addr_struct); int addrlen; if (check_ip_ver(local_addr) == 4) { addrlen = sizeof(struct sockaddr_in); } else if (check_ip_ver(local_addr) == 6) { addrlen = sizeof(struct sockaddr_in6); } else { exit(207); } listen(server_sock,50); /* Arbitrary number, change later */ printf("Listening on %s:%d\n",local_addr,local_port); struct sockaddr remote_addr_struct; while (1) { int from_client = accept(server_sock,&addr_struct,(socklen_t *)&addrlen); int to_server = create_remote(preferred_remote_network,preferred_transport,remote_addr,remote_port,&remote_addr_struct); printf("Connection established to %s:%d\n",remote_addr,remote_port); if (fork() == 0) { /* fork returns 0 for a child, so we're in the child's execution right now */ close(server_sock); if (fork() == 0) { forward_data(from_client,to_server); exit(0); } if (fork() == 0) { forward_data(to_server,from_client); exit(0); } exit(0); } } }