A simple HTTP proxy program under Linux C __linux

Source: Internet
Author: User
Tags connect socket get ip sin htons

The principle of HTTP proxy server is not complicated, that is, the HTTP protocol header passed by the client browser is forwarded to the Web server, and the data returned by the Web server is forwarded to the client browser, which plays a role as a relay station.

The following is an example of an HTTP protocol header:

Get http://www.google.com.hk/HTTP/1.1
Host:www.google.com.hk
Proxy-connection:keep-alive
user-agent:mozilla/5.0 (X11; U Linux i686; En-US) applewebkit/533.4 (khtml, like Gecko) chrome/5.0.375.70 safari/533.4
accept:application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-encoding:gzip,deflate,sdch
accept-language:en-us,en;q=0.8
accept-charset:iso-8859-1,utf-8;q=0.7,*;q=0.3


There is a blank line behind the protocol header.

The role of the proxy server is to send this data to "Host:" After the address specified, here is "www.google.com.hk". In addition, because this is the browser to the agent's protocol header, so the third line is: "Proxy-connection:keep-alive", if the direct connection to the Web server, you need to use "connection:keep-alive."

According to the above principle, the procedure is as follows:

#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <string.h> #include <netdb.h> #include "mystr.h"/* inside has its own write string handler function */int main ( void) {struct sockaddr_in webin,sin,cin,*temp;/*webin the address structure used when connecting to the Web server, the address structure used by the sin agent itself, the address structure of the CIN client/int C_sock,s_ Sock,tc_sock;/*c_sock used to connect the Web server, S_sock used to monitor the proxy client's listening sockets, Tc_sock connect socket/int count,total=0,m=0,k=0;/* to connect the proxy client. Count is used to save the size of the recv function each time, total save size, M save total number of megabytes, K save K-level data number/socklen_t len=0;/* This is the size of the client address, is the accept function of the third parameter * * Char ip[16 ];/* Client IP address/char buf[10240];/* cache 10k*/Char headerstr[1024];/* client-side HTTP protocol Header/Char host[50];/* destination host */char port_c[5] /* Port/struct addrinfo *res;/* connection DNS server, the address structure returned after resolving domain name sin.sin_family=af_inet; Sin.sin_port=htons (8000);/* Monitor 8000 Port * * * SIN.SIN_ADDR.S_ADDR=INADDR_ANY; if ((S_sock=socket (af_inet,sock_stream,0)) ==-1)/* Establish a listening socket/{perror ("failed to create S_sock"); exit (1);} if (Bind S_ Sock, (struct sockaddr*) &sin,sizeof (sin)) ==-1) {perror ("Failed to bind S_sock"); exit (1);} listen (s_sock,100); printf ("waiting.../n"); while (1) {if ((Tc_sock=accept (S_sock, (struct sockaddr*) &cin,&len)) ==-1) {perror (' failed to accept '); exit (1);} Inet_ntop (Af_inet,&cin,ip,len); printf ("A client connecting:%s/n", Ip); Begin to receive data from client recv (tc_sock,headerstr,sizeof (HEADERSTR), 0); printf ("%s/n", headerstr); Replace (HEADERSTR, "/r/nproxy-connection", "/r/nconnection");/* Write the string handler function/substring (HOST,STRSTR, "Headerstr," Host: "), 6,indexof (Strstr (Headerstr," Host: "),"/r/n ");/* intercept the contents of the" host: "String to the"/r/n "string, which is the Web server address for this client request/if ( LastIndexOf (Host, ":") ==-1)/*host does not contain a colon, indicating that no port number is specified * * * strcpy (Port_c, "80"); else {printf ("/t/t%s/n", host); substring (Port_c,host,lastindexof (host, ":") +1,strlen (host);///printf as the port number after the colon * * ("/t/t%s/n", host); SUBSTRING (host,host,0,lastindexof (host, ":"));//* To prefix the host domain name in front of the colon/if (atoi (port_c) ==0) {printf ("Port is not available:%") C/n ", Port_c); Continue printf ('%s connects to%s:%s/n ', Ip,hosT,port_c); if (C_sock=socket (af_inet,sock_stream,0) ==-1)/* socket used to connect to the Web server/{perror ("failed to create C_sock"); exit (1);}//* Start to pass HTTP protocol header to Web server, request data * * * webin.sin_family=af_inet; Webin.sin_port=htons (Atoi (Port_c)); if (getaddrinfo (host, "http", Null,&res) ==-1) {perror ("error to get IP from host name"); continue;} temp= (struct SOCKAD dr_in*) ((*res). ai_addr)/* Get the IP address of the Web server/webin.sin_addr= (*temp). sin_addr; Inet_ntop (af_inet,& (WEBIN.SIN_ADDR), ip,16); printf ("%s/n", IP);/* This is the IP address of the Web server/if (Connect (c_sock, (struct sockaddr*) &webin,sizeof (webin)) ==-1)/* Connect Web server/{perror ("Failed to connect to Web Server"); exit (1);} Send (C_sock,headerstr,sizeof (HEADERSTR), 0);/* Pass the protocol header to the Web server/printf ("Exchange data.../n"); do{count=recv (c_sock,buf,sizeof (BUF), 0)/* Receive data from the Web server/printf ("/t/tcount:%d/n", count); if (count==-1) {perror (" Failed to reveived data from server "); Break }else if (count==0) break; else Total+=count; if (send (tc_sock,buf,count,0) ==-1)/* Sending data to the client * * * PERROR ("Failed to SenD data to client "); Break }}while (count>0); if (total>1024) {k=k+total/1024; total=total%1024} if (k>1024) {m=m+k/1024; k=k%1024; printf ("~~~~~~~~send over,total:%d M%d K%d bytes/n", m,k,total); Close (C_sock); Close (Tc_sock); }} 

This program basically implements the function of the agent, but it is only a prototype, but also very imperfect, such as from the Web server to get data to the browser client, the use of blocking serial method, that is, from the Web server to obtain data and send data to the client at the same time only one, It is best to continue receiving data from the Web server when the program sends data to the browser. Of course, if the agent host and the Web server or the browser client on either side of the network connection speed, such as and proxy client in the same LAN, this effect is not significant.

In addition, the program is not stable, only a few web page program will exit, but no error. But it's not a big problem to hit a Google-like Web page. This program is of little practical value and is used only for research.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.