Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c# - Listen to Browser's requests

Using the following code:

HttpListener listener = new HttpListener();
//listener.Prefixes.Add("http://*:80/");
listener.Prefixes.Add("http://*:8080/");
listener.Prefixes.Add("http://*:8081/");
listener.Prefixes.Add("http://*:8082/");
listener.Start();
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;

The program hangs on the GetContext(); despite loading http (not https) pages in IE and Firefox.

When I uncomment the first line I get the error:

Failed to listen on prefix 'http://*:80/' because it conflicts with an existing registration on the machine.

So how do I listen to a browser's requests?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@L.B I want to write a "proxy"

Don't reinvent the wheel and just use the FiddlerCore

public class HttpProxy : IDisposable
{
    public HttpProxy()
    {
        Fiddler.FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
        Fiddler.FiddlerApplication.Startup(8764, true, true);
    }

    void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
    {
        Console.WriteLine(String.Format("REQ: {0}", oSession.url));
    }

    public void Dispose()
    {
        Fiddler.FiddlerApplication.Shutdown();
    }
}

EDIT

You can start with this rectangular wheel :)

void SniffPort80()
{
    byte[] input = new byte[] { 1 };
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
    socket.Bind(new IPEndPoint(IPAddress.Broadcast, 80));
    socket.IOControl(IOControlCode.ReceiveAll, input, null);

    byte[] buffer = new byte[0x10000];

    Task.Factory.StartNew(() =>
        {
            while (true)
            {
                int len = socket.Receive(buffer);
                if (len <= 40) continue; //Poor man's check for TCP payload
                string bin = Encoding.UTF8.GetString(buffer, 0, len); //Don't trust to this line. Encoding may be different :) even it can contain binary data like images, videos etc.
                Console.WriteLine(bin);
            }
        });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...