如何劫持所有本地http请求并使用c提取url?

Gtk*_*ker 6 c http winpcap

我应该去哪个方向(图书馆,文件)?

UPDATE

有人可以说明如何使用winpcap来完成这项工作吗?

更新2

如何验证数据包是否是HTTP数据包?

bri*_*ner 15

如果通过"劫持"你意味着嗅探数据包,那么你应该用WinPcap做什么,如下:

  1. 找到您要使用的设备 - 请参阅WinPcap教程.

  2. 使用打开设备 pcap_open

    // Open the device
    char errorBuffer[PCAP_ERRBUF_SIZE];
    pcap_t *pcapDescriptor = pcap_open(source,                // name of the device
                                       snapshotLength,        // portion of the packet to capture
                                                              // 65536 guarantees that the whole packet will be captured on all the link layers
                                       attributes,            // 0 for no flags, 1 for promiscuous
                                       readTimeout,           // read timeout
                                       NULL,                  // authentication on the remote machine
                                       errorBuffer);          // error buffer
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用从描述符中读取数据包的函数 pcap_loop

    int result = pcap_loop(pcapDescriptor, count, functionPointer, NULL);
    
    Run Code Online (Sandbox Code Playgroud)

    这将循环,直到发生错误或使用特殊方法调用中断循环.它将为每个数据包调用functionPointer.

  4. 在函数指向实现解析数据包的东西,它应该看起来像pcap_handler:

    typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *,
             const u_char *);
    
    Run Code Online (Sandbox Code Playgroud)
  5. 现在你剩下的就是解析它们的缓冲区所在的数据包,它们const u_char*的长度在pcap_pkthdr结构caplen字段中.

    假设您通过TCP over IPv4 over Ethernet数据包进行HTTP GET,您可以:

    • 跳过以太网报头的14个字节.
    • 跳过20个字节的IPv4报头(假设没有IPv4的选项,如果你怀疑IPv4的选择是可能的,你可以阅读IPv4报头的5-8位,乘上4,这将是字节的数量IPv4标头需要).
    • 跳过20个字节的TCP标头(假设没有TCP选项,如果您怀疑TCP选项是可能的,您可以读取TCP标头的96-99位,将其乘以4,这将是字节数TCP标头需要).
    • 数据包的其余部分应该是HTTP文本.第一个和第二个空格之间的文本应该是URI.如果它太长,您可能需要进行一些TCP重建,但是大多数URI都足够小以适应一个数据包.

      更新:在代码中,这看起来就像那样(我在没有测试的情况下编写它):

      int tcp_len, url_length;
      uchar *url, *end_url, *final_url, *tcp_payload;
      
      ... /* code in http://www.winpcap.org/docs/docs_40_2/html/group__wpcap__tut6.html */
      
      /* retireve the position of the tcp header */
      ip_len = (ih->ver_ihl & 0xf) * 4;
      
      /* retireve the position of the tcp payload */
      tcp_len = (((uchar*)ih)[ip_len + 12] >> 4) * 4;
      tcpPayload = (uchar*)ih + ip_len + tcp_len;
      
      /* start of url - skip "GET " */
      url = tcpPayload + 4;
      
      /* length of url - lookfor space */
      end_url = strchr((char*)url, ' ');
      url_length = end_url - url;
      
      /* copy the url to a null terminated c string */
      final_url = (uchar*)malloc(url_length + 1);
      strncpy((char*)final_url, (char*)url, url_length);
      final_url[url_length] = '\0';
      
      Run Code Online (Sandbox Code Playgroud)

您还可以使用创建和设置BPF来仅过滤HTTP流量.请参阅WinPcap教程.您应该使用过滤器"tcp and dst port 80",它只会向您提供计算机发送给服务器的请求.

如果您不介意使用C#,可以尝试使用Pcap.Net,它可以更轻松地为您完成所有这些工作,包括解析数据包的以太网,IPv4和TCP部分.