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

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

UPDATE

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

更新2

如何validation数据包是否为HTTP?

如果通过“劫持”你意味着嗅探数据包,那么你应该用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 
  3. 使用从pcap_loop描述符中读取数据包的函数

     int result = pcap_loop(pcapDescriptor, count, functionPointer, NULL); 

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

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

     typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *, const u_char *); 
  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'; 

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

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

试试http://www.winpcap.org/

这可能听起来有点矫枉过正,但Web代理/缓存服务器Squid确实如此。 几年前,我的公司使用它,我必须在本地调整代码,以便在访问某些URL时提供一些特殊警告,因此我知道它可以做你想要的。 您只需找到所需的代码并将其拉出来用于您的项目。 我使用的是版本2.X,我现在看到它们已达到3.X但我怀疑代码方面内部没有太大变化。

你没有说windows是’要求’还是’偏好’,但根据网站: http : //www.squid-cache.org/他们可以做到这两点。

您可能需要查看tcpdump的源代码以了解它是如何工作的。 tcpdump是一个Linux命令行实用程序,用于监视和打印网络活动。 但是,您需要root权限才能使用它。