-
在Ubuntu系统下,安装所需的库,sudo apt install libpcap-dev;
-
编写捕获UDP数据包的代码,文件名capture_udp.c:
#include <pcap.h> #include <stdio.h> #include <stdlib.h> #include <arpa/inet.h> void packet_handler(u_char *user_data, const struct pcap_pkthdr *pkthdr, const u_char *packet) { struct ether_header *eth_header; struct ip *ip_header; struct udphdr *udp_header; eth_header = (struct ether_header *)packet; ip_header = (struct ip *)(packet + sizeof(struct ether_header)); udp_header = (struct udphdr *)(packet + sizeof(struct ether_header) + sizeof(struct ip)); if (ip_header->ip_p == IPPROTO_UDP) { printf("UDP Packet Captured:\n"); printf("Source IP: %s\n", inet_ntoa(ip_header->ip_src)); printf("Destination IP: %s\n", inet_ntoa(ip_header->ip_dst)); printf("Source Port: %d\n", ntohs(udp_header->uh_sport)); printf("Destination Port: %d\n", ntohs(udp_header->uh_dport)); printf("UDP Length: %d\n", ntohs(udp_header->uh_ulen)); } } int main(int argc, char *argv[]) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *handle; const char *dev = "eth0"; // 替换为你要捕获的网络接口 handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf); if (handle == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf); return 2; } if (pcap_datalink(handle) != DLT_EN10MB) { fprintf(stderr, "Device %s doesn't provide Ethernet headers - not supported\n", dev); return 2; } pcap_loop(handle, -1, packet_handler, NULL); pcap_close(handle); return 0; }
-
发送UDP数据包,文件名send_udp.c:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { int sockfd; struct sockaddr_in dest_addr; char *message = "Hello, UDP!"; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket"); exit(1); } memset(&dest_addr, 0, sizeof(dest_addr)); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(12345); // 目标端口 inet_pton(AF_INET, "127.0.0.1", &dest_addr.sin_addr); // 目标IP地址 if (sendto(sockfd, message, strlen(message), 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0) { perror("sendto"); exit(1); } printf("UDP packet sent successfully.\n"); close(sockfd); return 0; }
-
编译和运行
-
编译捕获UDP数据包的代码:
gcc -o capture_udp capture_udp.c -lpcap
-
编译发送UDP数据包的代码:
gcc -o send_udp send_udp.c
-
运行捕获UDP数据包的程序:
sudo ./capture_udp
-
运行发送UDP数据包的程序:
./send_udp
-
注意事项:
-
捕获数据包的程序需要以
root
权限运行,因为libpcap
需要访问网络接口。 -
发送 UDP 数据包的程序不需要
root
权限,但需要确保目标 IP 和端口是正确的。 -
在实际应用中,可能需要处理更多的错误情况和边界条件。
-
-
05-14
2588
