Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- simple proxy using libuv
- */
- #include "../uv/uv.h"
- #include "../uvhelper.h"
- #include <stdio.h>
- #include <stdlib.h>
- #define CLIENT_PORT 8000
- #define SERVER_PORT 7171
- #define strh(x) #x
- #define str(x) strh(x)
- void on_client_connect(uv_stream_t *server, int status);
- uv_loop_t *loop;
- uv_tcp_t client, proxy, server;
- int main (void)
- {
- loop = uv_default_loop();
- uv_tcp_init(loop, &client);
- uv_tcp_init(loop, &server);
- uv_tcp_init(loop, &proxy);
- struct sockaddr_in bind_addr;
- uv_ip4_addr("0.0.0.0", CLIENT_PORT, &bind_addr);
- uv_tcp_bind(&proxy, (const struct sockaddr *)&bind_addr, 0);
- uv_listen((uv_stream_t *)&proxy, SOMAXCONN, on_client_connect);
- printf(":: Listening on all interfaces @port=" str(SERVER_PORT) "\n");
- uv_run(loop, UV_RUN_DEFAULT);
- }
- void read_from_client(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
- {
- printf("%s = %d bytes\n", __func__, nread);
- if (nread > 0)
- {
- uv_easy_write((uv_stream_t *)&server, -1,
- &(uv_buf_t) {.base = buf->base, .len = nread}
- );
- }
- }
- void read_from_server(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
- {
- printf("%s = %d bytes\n", __func__, nread);
- if (nread > 0)
- {
- printf(strh(__func__) "= %u bytes\n", nread);
- if (nread > 0)
- {
- uv_easy_write((uv_stream_t *)&client, -1,
- &(uv_buf_t) {.base = buf->base, .len = nread}
- );
- }
- }
- void on_server_connect(uv_connect_t *con, int status)
- {
- printf("Server connection established.\n");
- uv_read_start((uv_stream_t *) &server, alloc_buffer, read_from_server);
- if (uv_accept((uv_stream_t *)&proxy, (uv_stream_t *) &client) == 0)
- {
- uv_read_start((uv_stream_t *) &client, alloc_buffer, read_from_client);
- }
- else
- {
- printf("error in on_servc");
- uv_close((uv_handle_t *) &proxy, NULL);
- }
- }
- void on_client_connect(uv_stream_t *proxyq, int status)
- {
- printf("Client connection established\n");
- struct sockaddr_in bind_addr;
- uv_ip4_addr("127.0.0.1", SERVER_PORT, &bind_addr);
- uv_connect_t *connect = malloc(sizeof(uv_connect_t));
- uv_tcp_connect(connect, &server, (const struct sockaddr *)&bind_addr,
- on_server_connect);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement