c写一个socket抓包
时间: 2024-05-04 07:18:23 浏览: 7
以下是一个简单的使用 socket 抓包的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#define BUFFER_SIZE 65536
void print_packet(unsigned char* buffer, int size) {
struct iphdr *iph = (struct iphdr*)buffer;
unsigned short iphdrlen = iph->ihl * 4;
struct tcphdr *tcph = (struct tcphdr*)(buffer + iphdrlen);
printf("Source IP: %s\n", inet_ntoa(*(struct in_addr*) &iph->saddr));
printf("Destination IP: %s\n", inet_ntoa(*(struct in_addr*) &iph->daddr));
printf("Source Port: %d\n", ntohs(tcph->source));
printf("Destination Port: %d\n", ntohs(tcph->dest));
printf("Data: ");
for(int i = iphdrlen + tcph->doff * 4; i < size; i++) {
printf("%c", buffer[i]);
}
printf("\n\n");
}
int main() {
int sock_raw = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
if(sock_raw < 0) {
printf("Socket creation error\n");
return 1;
}
unsigned char buffer[BUFFER_SIZE];
int buffer_len;
while(1) {
buffer_len = recvfrom(sock_raw, buffer, BUFFER_SIZE, 0, NULL, NULL);
if(buffer_len < 0) {
printf("Packet receive error\n");
return 1;
}
print_packet(buffer, buffer_len);
}
close(sock_raw);
return 0;
}
```
该程序使用原始套接字(raw socket)来监听所有传入的 TCP 数据包。当接收到一个数据包时,程序会打印出源 IP 地址、目标 IP 地址、源端口、目标端口以及数据内容。
请注意,使用原始套接字需要在 root 权限下运行。另外,这只是一个简单的示例,实际使用时需要考虑更多的细节和安全问题。