libnet库使用
libnet库
libnet 库主要用 C 语言实现,提供了低层网络数据包的构造、处理和发送功能。
libnet的开发目的是建立一个简单统一的网络编程接口以屏蔽不同操作系统低层网络编程的差别,使得程序员将精力集中在解决关键问题上。
特点如下:
高层接口:libnet被用于提取低 层数据报转移的专用体系结构细节。
低层数据报构建:libnet的一个主要特点就是它完全控制每个数据报的头域。
可移植性的接口:与具体的操作系统平台无关。libnet目前可以在Windows、Linux、OS、FreeBSD、Solaris等操作系统上运行,并且提供了统一的接口。
数据包构造:libnet提供了一系列的TCP/IP数据报文的构造函数以方便用户使用。
数据包的处理:libnet提供了一系列处理底层网络编程的辅助函数,利用这些辅助函数,帮助用户简化那些烦琐的事务性的编程工作。
数据包发送:libnet允许用户在两种不同的数据包发送方法中选择。
libnet支持TCP/IP协议族中的所有协议。
libnet函数库提供的接口函数包含 15 种数据包生成器和两种数据包发送器(IP 层和数据链路层)。
编译libnet库
下载libnet
wget https://github.com/libnet/libnet/releases/download/v1.2/libnet-1.2.tar.gz
tar -xvf libnet-1.2.tar.gz
编译libnet
cd libnet-1.2
./configure --host=${TOOLCHAIN_PREFIX} --prefix=$INSTALL_PREFIX
make
make install
应用例子
发送UDP数据包
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libnet.h>
int main(int argc, charchar *argv[])
{
char send_msg[1000] = "";
char err_buf[100] = "";
libnet_t *lib_net = NULL;
int lens = 0;
libnet_ptag_t lib_t = 0;
//发送者网卡地址00:0c:29:97:c7:c1
unsigned char src_mac[6] = {0x00,0x0c,0x29,0x97,0xc7,0xc1};
//接收者网卡地址74-27-EA-B5-FF-D8
unsigned char dst_mac[6] = {0x74,0x27,0xea,0xb5,0xff,0xd8};
char *src_ip_str = "192.168.31.163"; //源主机IP地址
char *dst_ip_str = "192.168.31.248"; //目的主机IP地址
unsigned long src_ip,dst_ip = 0;
lens = sprintf(send_msg, "%s", "this is for the udp test");
lib_net = libnet_init(LIBNET_LINK_ADV, NULL, err_buf); //初始化
if(NULL == lib_net)
{
perror("libnet_init");
exit(-1);
}
src_ip = libnet_name2addr4(lib_net,src_ip_str,LIBNET_RESOLVE);
//将字符串类型的ip转换为顺序网络字节流
dst_ip = libnet_name2addr4(lib_net,dst_ip_str,LIBNET_RESOLVE);
//构造udp数据包
lib_t=libnet_build_udp(8080, 8080, 8+lens, 0, send_msg, lens, lib_net, 0);
//构造ip数据包
lib_t = libnet_build_ipv4(20+8+lens,0,500,0,10,17, 0, src_ip,dst_ip,NULL,0,lib_net, 0);
//构造以太网数据包
lib_t = libnet_build_ethernet((u_int8_t*)dst_mac,(u_int8_t *)src_mac,0x800,NULL,0,lib_net,0);
int res = 0;
//发送数据包
res = libnet_write(lib_net);
if(-1 == res)
{
perror("libnet_write");
exit(-1);
}
libnet_destroy(lib_net);
return 0;
}
作者:SteveChen 创建时间:2025-07-17 09:17
最后编辑:SteveChen 更新时间:2025-07-17 09:34
最后编辑:SteveChen 更新时间:2025-07-17 09:34