libnet入門

在Unix系統平臺上的網絡安全工具開發中,目前最爲流行的C API library有libnet、libpcap、libnids和libicmp等。它們分別從不同層次和角度提供了不同的功能函數。使網絡開發人員能夠忽略網絡底層細節的實現,從而專注於程序本身具體功能的設計與開發。其中,
* libnet提供的接口函數主要實現和封裝了數據包的構造和發送過程。 
* libpcap提供的接口函數主要實現和封裝了與數據包截獲有關的過程。 
* libnids提供的接口函數主要實現了開發網絡入侵監測系統所必須的一些結構框架。 
* libicmp等相對較爲簡單,它封裝的是ICMP數據包的主要處理過程(構造、發送、接收等)。 利用這些C函數庫的接口,網絡安全工具開發人員可以很方便地編寫出具有結構化強、健壯性好、可移植性高等特點的程序,如scanner、sniffer、firewall、IDS等。
---[[ libnet ]]------------------------------------------ 
libnet庫的最新版本爲1.0.0(最新版已經到1.1.6),它一共約7600行C源代碼,33個源程序文件,12個C頭文件,50餘個自定義函數,提供的接口函數包含15種數據包生成器和兩種數據包發送器(IP層和數據鏈路層)。目前只支持IPv4,不支持IPv6。已經過測試的系統平臺包括:
* OpenBSD 2.6snap, 2.5, 2.4, 2.3, 2.2 (i386) 
* FreeBSD 4.0-STABLE, 3.3-STABLE, 3.2-RELEASE, 3.1-CURRENT, 3.0, 2.2 (i386) 
* NetBSD 1.3.2 (i386) 
* BSD/OS 3.x (i386) 
* BSDi 3.0 (i386) 
* Linux 2.2.x, 2.0.3x, 2.1.124 (i386, alpha) (libc: 2.4.x, glibc: 2.0.x) 
* Solaris 7 (SPARC, gcc 2.7.2[13], 2.8.2), 2.6 (SPARC, gcc 2.8.2), 
2.5.x (SPARC, gcc 2.7.2[13]) 
* IRIX 6.2 
* MacOS 5.3rhapsody (powerpc) 
libnet提供的接口函數按其作用可分爲四類:

* 內存管理(分配和釋放)函數
* 地址解析函數
* 數據包構造函數
* 數據包發送函數

以下分別列出這些接口函數及其功能(其參數含義簡單易懂,不再解釋):


★ 內存管理函數

單數據包內存初始化:(這1.1.6版本中這些函數已經被去掉
int libnet_init_packet(u_short packet_size, u_char **buf);

單數據包內存釋放:
void libnet_destroy_packet(u_char **buf);

多數據包內存初始化:
int libnet_init_packet_arena(struct libnet_arena **arena, 
u_short packet_num, u_short packet_size);

訪問多數據包內存中的下一個數據包:
u_char *libnet_next_packet_from_arena(struct libnet_arena **arena, 
u_short packet_size);

多數據包內存釋放:
void libnet_destroy_packet_arena(struct libnet_arena **arena);


★ 地址解析函數

解析主機名:
u_char *libnet_host_lookup(u_long ip, u_short use_name);

解析主機名(可重入函數): 
void libnet_host_lookup_r(u_long ip, u_short use_name, u_char *buf);

域名解析:
u_long libnet_name_resolve(u_char *ip, u_short use_name);

獲取接口設備IP地址:
u_long libnet_get_ipaddr(struct libnet_link_int *l, 
const u_char *device, const u_char *ebuf);

獲取接口設備硬件地址:
struct ether_addr *libnet_get_hwaddr(struct libnet_link_int *l, 
const u_char *device, 
const u_char *ebuf);


★ 數據包構造函數

ARP協議數據包:
int libnet_build_arp(u_short hrdw, u_short prot, u_short h_len,
u_short p_len, u_short op, u_char *s_ha,
u_char *s_pa, u_char *t_ha, u_char *t_pa,
const u_char *payload, int payload_len,
u_char *packet_buf);

DNS協議數據包:
int libnet_build_dns(u_short id, u_short flags, u_short num_q,
u_short num_answ_rr, u_short num_auth_rr,
u_short num_add_rr, const u_char * payload,
int payload_len, u_char *packet_buf);

以太網協議數據包:
int libnet_build_ethernet(u_char *daddr, u_char *saddr, u_short id,
const u_char *payload, int payload_len,
u_char *packet_buf);

ICMP協議數據包(ICMP_ECHO / ICMP_ECHOREPLY):
int libnet_build_icmp_echo(u_char type, u_char code, u_short id,
u_short seq, const u_char *payload,
int payload_len, u_char *packet_buf);

ICMP協議數據包(ICMP_MASKREQ / ICMP_MASKREPLY):
int libnet_build_icmp_mask(u_char type, u_char code, u_short id,
u_short seq, u_long mask,
const u_char *payload, int payload_len,
u_char *packet_buf);

ICMP協議數據包(ICMP_UNREACH):
int libnet_build_icmp_unreach(u_char type, u_char code,
u_short orig_len, u_char orig_tos,
u_short orig_id, u_short orig_frag,
u_char orig_ttl, u_char orig_prot,
u_long orig_saddr, u_long orig_daddr,
const u_char *payload, int payload_len,
u_char *packet_buf);

ICMP協議數據包(ICMP_TIMEXCEED):
int libnet_build_icmp_timeexceed(u_char type, u_char code,
u_short orig_len, u_char orig_tos,
u_short orig_id, u_short orig_frag,
u_char orig_ttl, u_char orig_prot,
u_long orig_saddr, u_long orig_daddr,
const u_char *payload, int payload_len,
u_char *packet_buf);

ICMP協議數據包(ICMP_REDIRECT):
int libnet_build_icmp_redirect(u_char type, u_char code, u_long gateway,
u_short orig_len, u_char orig_tos,
u_short orig_id, u_short orig_frag,
u_char orig_ttl, u_char orig_prot,
u_long orig_saddr, u_long orig_daddr,
const u_char *payload, int payload_len,
u_char *packet_buf);

ICMP協議數據包(ICMP_TSTAMP / ICMP_TSTAMPREPLY):
int libnet_build_icmp_timestamp(u_char type, u_char code, u_short id,
u_short seq, n_time otime, n_time rtime,
n_time ttime, const u_char *payload,
int payload_len, u_char *packet_buf);

IGMP協議數據包:
int libnet_build_igmp(u_char type, u_char code, u_long ip,
const u_char *payload, int payload_len,
u_char *packet_buf);

IP協議數據包:
int libnet_build_ip(u_short len, u_char tos, u_short ip_id, u_short frag,
u_char ttl, u_char protocol, u_long saddr,
u_long daddr, const u_char *payload, int payload_len,
u_char *packet_buf);

OSPF路由協議數據包:
int libnet_build_ospf(u_short len, u_char type, u_long router_id,
u_long area_id, u_short auth_type,
const char *payload, int payload_s, u_char *buf);

OSPF路由協議數據包(Hello):
int libnet_build_ospf_hello(u_long netmask, u_short interval,
u_char options, u_char priority,
u_int dead_interval, u_long des_router,
u_long backup, u_long neighbor,
const char *payload, int payload_s,
u_char *buf);

OSPF路由協議數據包(DataBase Description (DBD)):
int libnet_build_ospf_dbd(u_short len, u_char options, u_char type,
u_int sequence_num, const char *payload,
int payload_s, u_char *buf);

OSPF路由協議數據包(Link State Request (LSR)):
int libnet_build_ospf_lsr(u_int type, u_int ls_id, u_long adv_router,
const char *payload, int payload_s,
u_char *buf);

OSPF路由協議數據包(Link State Update (LSU)):
int libnet_build_ospf_lsu(u_int num, const char *payload,
int payload_s, u_char *buf);

OSPF路由協議數據包(Link State Acknowledgement (LSA)):
int libnet_build_ospf_lsa(u_short age, u_char options, u_char type,
u_int ls_id, u_long adv_router,
u_int sequence_num, u_short len,
const char *payload, int payload_s,
u_char *buf);

OSPF路由協議數據包(OSPF Link Sate NetworkLink State Router):
int libnet_build_ospf_lsa_net(u_long netmask, u_int router_id,
const char *payload, int payload_s,
u_char *buf);

OSPF路由協議數據包(Link State Router):
int libnet_build_ospf_lsa_rtr(u_short flags, u_short num, u_int id,
u_int data, u_char type, u_char tos,
u_short metric, const char *payload,
int payload_s, u_char *buf);

OSPF路由協議數據包(Link State Summary):
int libnet_build_ospf_lsa_sum(u_long netmask, u_int metric, u_int tos,
const char *payload, int payload_s,
u_char *buf);

OSPF路由協議數據包(Link State AS External):
int libnet_build_ospf_lsa_as(u_long netmask, u_int metric,
u_long fwd_addr, u_int tag,
const char *payload, int payload_s,
u_char *buf);

RIP路由協議數據包:
int libnet_build_rip(u_char cmd, u_char ver, u_short domain,
u_short addr_fam, u_short route_tag, u_long ip,
u_long mask, u_long next_hop, u_long metric,
const u_char *payload, int payload_len,
u_char *packet_buf);

TCP協議數據包:
int libnet_build_tcp(u_short th_sport, u_short th_dport, u_long th_seq,
u_long th_ack, u_char th_flags, u_short th_win,
u_short th_urg, const u_char *payload,
int payload_len, u_char *packet_buf);

UDP協議數據包:
int libnet_build_udp(u_short sport, u_short dport, const u_char *payload,
int payload_len, u_char *packet_buf);

IP協議數據包選項:
int libnet_insert_ipo(struct ipoption *opt, u_char opt_len,
u_char *packet_buf);

TCP協議數據包選項:
int libnet_insert_tcpo(struct tcpoption *opt, u_char opt_len,
u_char *packet_buf);


★ 數據包發送函數

打開raw socket:
int libnet_open_raw_sock(int protocol);

關閉raw socket:
int libnet_close_raw_sock(int socket);

選擇接口設備:
int libnet_select_device(struct sockaddr_in *sin, 
u_char **device, u_char *ebuf);

打開鏈路層接口設備:
struct libnet_link_int *libnet_open_link_interface(char *device,
char *ebuf);

關閉鏈路層接口設備:
int libnet_close_link_interface(struct libnet_link_int *l);

發送IP數據包:
int libnet_write_ip(int socket, u_char *packet, int packet_size);

發送鏈路層數據包:
int libnet_write_link_layer(struct libnet_link_int *l,
const u_char *device, u_char *packet,
int packet_size);

檢驗和計算:
int libnet_do_checksum(u_char *packet, int protocol, int packet_size);


★ 相關的支持函數

隨機數種子生成器:
int libnet_seed_prand();

獲取隨機數:
u_long libnet_get_prand(int modulus);

16進制數據輸出:
void libnet_hex_dump(u_char * buf, int len, int swap, FILE *stream);

端口列表鏈初始化:
int libnet_plist_chain_new(struct libnet_plist_chain **plist,
char *token_list);

獲取端口列表鏈的下一項(端口範圍):
int libnet_plist_chain_next_pair(struct libnet_plist_chain *plist,
u_short *bport, u_short *eport);

端口列表鏈輸出顯示:
int libnet_plist_chain_dump(struct libnet_plist_chain *plist);

獲取端口列表鏈:
u_char *libnet_plist_chain_dump_string(struct libnet_plist_chain *plist);

端口列表鏈內存釋放:
void libnet_plist_chain_free(struct libnet_plist_chain *plist);


★ 數據常量

==================================================================================
數據包頭大小定義:

常量名 數值(字節數) 
LIBNET_ARP_H 28 
LIBNET_DNS_H 12 
LIBNET_ETH_H 14 
LIBNET_ICMP_H 4 
LIBNET_ICMP_ECHO_H 8 
LIBNET_ICMP_MASK_H 12 
LIBNET_ICMP_UNREACH_H 8 
LIBNET_ICMP_TIMXCEED_H 8 
LIBNET_ICMP_REDIRECT_H 8 
LIBNET_ICMP_TS_H 20 
LIBNET_IGMP_H 8 
LIBNET_IP_H 20 
LIBNET_RIP_H 24 
LIBNET_TCP_H 20 
LIBNET_UDP_H 8

==================================================================================
數據包內存常量:

常量名 含義
LIBNET_PACKET TCP/UDP數據包頭 + IP數據包頭使用的內存
LIBNET_OPTS IP或TCP選項使用的內存 
LIBNET_MAX_PACKET IP_MAXPACKET (65535字節)使用的內存

==================================================================================
隨機數發生器常量(libnet_get_prand()函數使用):

常量名 數值
LIBNET_PRAND_MAX 65535 
LIBNET_PR2 0 - 2 
LIBNET_PR8 0 - 255 
LIBNET_PR16 0 - 32767 
LIBNET_PRu16 0 - 65535 
LIBNET_PR32 0 - 2147483647 
LIBNET_PRu32 0 - 4294967295

==================================================================================
錯誤消息常量(libnet_error()函數使用):

常量名 含義 
LIBNET_ERR_WARNING 警告類型消息
LIBNET_ERR_CRITICAL 緊急類型消息
LIBNET_ERR_FATAL 致命錯誤消息

==================================================================================
libnet_host_lookup()、libnet_host_lookup_r()和libnet_name_resolve()函數使用的常量:

常量名 含義
LIBNET_DONT_RESOLVE 不將IP地址解析爲FQDN名 
LIBNET_RESOLVE 嘗試將IP地址解析爲FQDN名

==================================================================================
宏定義

宏名 功能
LIBNET_GET_ARENA_SIZE(arena) 返回多數據包內存緩衝區大小(字節數)
LIBNET_GET_ARENA_REMAINING_BYTES(arena) 返回多數據包內存緩衝區剩餘空間大小(字節數)
LIBNET_PRINT_ETH_ADDR(e) 輸出顯示ether_addr結構中的以太網地址

==================================================================================


---[[ libnet應用實例 ]]----------------------------------

利用libnet函數庫開發應用程序的基本步驟非常簡單:

1、數據包內存初始化;
2、網絡接口初始化;
3、構造所需數據包;
4、計算數據包檢驗和;
5、發送數據包;
6、關閉網絡接口;
7、釋放數據包內存。

以下是四個使用了libnet接口函數編寫的數據包發送程序。在編譯前必須確保libnet庫已成功安裝。

例一:

  1. /* Example 1 [raw socket api - TCP packet] */  
  2. /* gcc -Wall `libnet-config --defines` libnet-example-x.c -o libnet-example-x \  
  3. `libnet-config --libs` */  
  4.   
  5. #include <libnet.h>  
  6.   
  7. void usage(char *);  
  8.   
  9. int main(int argc, char **argv)   
  10. {   
  11.     int network, /* our network interface */   
  12.         packet_size, /* packet size */   
  13.         c; /* misc */   
  14.     u_long src_ip, dst_ip; /* ip addresses */   
  15.     u_short src_prt, dst_prt; /* ports */   
  16.     u_char *cp, *packet; /* misc / packet */  
  17.   
  18.     printf("libnet example code:\tmodule 1\n\n");   
  19.     printf("packet injection interface:\traw socket\n");   
  20.     printf("packet type:\t\t\tTCP [no payload]\n");  
  21.   
  22.     src_ip = 0;   
  23.     dst_ip = 0;   
  24.     src_prt = 0;   
  25.     dst_prt = 0;  
  26.   
  27.     while((c = getopt(argc, argv, "d:s:")) != EOF)   
  28.     {   
  29.         switch (c)   
  30.         {   
  31.             /*  
  32.             * We expect the input to be of the form `ip.ip.ip.ip.port`. We  
  33.             * point cp to the last dot of the IP address/port string and  
  34.             * then seperate them with a NULL byte. The optarg now points to  
  35.             * just the IP address, and cp points to the port.  
  36.             */   
  37.         case 'd':   
  38.             if (!(cp = strrchr(optarg, '.')))   
  39.             {   
  40.                 usage(argv[0]);   
  41.             }   
  42.             *cp++ = 0;   
  43.             dst_prt = (u_short)atoi(cp);   
  44.             if (!(dst_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  45.             {   
  46.                 libnet_error(LIBNET_ERR_FATAL,   
  47.                     "Bad destination IP address: %s\n", optarg);   
  48.             }   
  49.             break;   
  50.         case 's':   
  51.             if (!(cp = strrchr(optarg, '.')))   
  52.             {   
  53.                 usage(argv[0]);   
  54.             }   
  55.             *cp++ = 0;   
  56.             src_prt = (u_short)atoi(cp);   
  57.             if (!(src_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  58.             {   
  59.                 libnet_error(LIBNET_ERR_FATAL,   
  60.                     "Bad source IP address: %s\n", optarg);   
  61.             }   
  62.             break;   
  63.         }   
  64.     }   
  65.     if (!src_ip || !src_prt || !dst_ip || !dst_prt)   
  66.     {   
  67.         usage(argv[0]);   
  68.         exit(EXIT_FAILURE);   
  69.     }  
  70.   
  71.     /*  
  72.     * We're just going to build a TCP packet with no payload using the  
  73.     * raw sockets API, so we only need memory for a TCP header and an IP  
  74.     * header.  
  75.     */   
  76.     packet_size = LIBNET_IP_H + LIBNET_TCP_H;  
  77.   
  78.     /*  
  79.     * Step 1: Memory initialization (interchangable with step 2).  
  80.     */   
  81.     libnet_init_packet(packet_size, &packet);   
  82.     if (packet == NULL)   
  83.     {   
  84.         libnet_error(LIBNET_ERR_FATAL, "libnet_init_packet failed\n");   
  85.     }  
  86.   
  87.     /*  
  88.     * Step 2: Network initialization (interchangable with step 1).  
  89.     */   
  90.     network = libnet_open_raw_sock(IPPROTO_RAW);   
  91.     if (network == -1)   
  92.     {   
  93.         libnet_error(LIBNET_ERR_FATAL, "Can't open network.\n");   
  94.     }  
  95.   
  96.     /*  
  97.     * Step 3: Packet construction (IP header).  
  98.     */   
  99.     libnet_build_ip(LIBNET_TCP_H, /* size of the packet sans IP header */   
  100.         IPTOS_LOWDELAY, /* IP tos */   
  101.         242, /* IP ID */   
  102.         0, /* frag stuff */   
  103.         48, /* TTL */   
  104.         IPPROTO_TCP, /* transport protocol */   
  105.         src_ip, /* source IP */   
  106.         dst_ip, /* destination IP */   
  107.         NULL, /* payload (none) */   
  108.         0, /* payload length */   
  109.         packet); /* packet header memory */  
  110.   
  111.     /*  
  112.     * Step 3: Packet construction (TCP header).  
  113.     */   
  114.     libnet_build_tcp(src_prt, /* source TCP port */   
  115.         dst_prt, /* destination TCP port */   
  116.         0xa1d95, /* sequence number */   
  117.         0x53, /* acknowledgement number */   
  118.         TH_SYN, /* control flags */   
  119.         1024, /* window size */   
  120.         0, /* urgent pointer */   
  121.         NULL, /* payload (none) */   
  122.         0, /* payload length */   
  123.         packet + LIBNET_IP_H); /* packet header memory */  
  124.   
  125.     /*  
  126.     * Step 4: Packet checksums (TCP header only).  
  127.     */   
  128.     if (libnet_do_checksum(packet, IPPROTO_TCP, LIBNET_TCP_H) == -1)   
  129.     {   
  130.         libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");   
  131.     }  
  132.   
  133.     /*  
  134.     * Step 5: Packet injection.  
  135.     */   
  136.     c = libnet_write_ip(network, packet, packet_size);   
  137.     if (c < packet_size)   
  138.     {   
  139.         libnet_error(LN_ERR_WARNING,   
  140.             "libnet_write_ip only wrote %d bytes\n", c);   
  141.     }   
  142.     else   
  143.     {   
  144.         printf("construction and injection completed, wrote all %d bytes\n", c);   
  145.     }  
  146.   
  147.     /*  
  148.     * Shut down the interface.  
  149.     */   
  150.     if (libnet_close_raw_sock(network) == -1)   
  151.     {   
  152.         libnet_error(LN_ERR_WARNING,   
  153.             "libnet_close_raw_sock couldn't close the interface");   
  154.     }  
  155.   
  156.   
  157.     /*  
  158.     * Free packet memory.  
  159.     */   
  160.     libnet_destroy_packet(&packet);  
  161.   
  162.     return (c == -1 ? EXIT_FAILURE : EXIT_SUCCESS);   
  163. }  
  164.   
  165.   
  166. void usage(char *name)   
  167. {   
  168.     fprintf(stderr, "usage: %s -s s_ip.s_port -d d_ip.d_port\n", name);   
  169. }  

 

例二:

  1. /* Example 2 [link layer api - ICMP_MASK] */  
  2. /* gcc -Wall `libnet-config --defines` libnet-example-x.c -o libnet-example-x `libnet-config --libs` */  
  3.   
  4. #include <libnet.h>  
  5.   
  6. void usage(char *);  
  7.   
  8. u_char enet_src[6] = {0x0d, 0x0e, 0x0a, 0x0d, 0x00, 0x00};   
  9. u_char enet_dst[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};  
  10.   
  11. int   
  12. main(int argc, char *argv[])   
  13. {   
  14.     int packet_size, /* size of our packet */   
  15.         c; /* misc */   
  16.     u_long src_ip, dst_ip; /* source ip, dest ip */   
  17.     u_char *packet; /* pointer to our packet buffer */   
  18.     char err_buf[LIBNET_ERRBUF_SIZE]; /* error buffer */   
  19.     u_char *device; /* pointer to the device to use */   
  20.     struct libnet_link_int *network; /* pointer to link interface struct */  
  21.   
  22.     printf("libnet example code:\tmodule 2\n\n");   
  23.     printf("packet injection interface:\tlink layer\n");   
  24.     printf("packet type:\t\t\tICMP net mask [no payload]\n");  
  25.   
  26.     device = NULL;   
  27.     src_ip = 0;   
  28.     dst_ip = 0;  
  29.   
  30.     while ((c = getopt(argc, argv, "i:d:s:")) != EOF)   
  31.     {   
  32.         switch (c)   
  33.         {   
  34.         case 'd':   
  35.             if (!(dst_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  36.             {   
  37.                 libnet_error(LIBNET_ERR_FATAL,   
  38.                     "Bad destination IP address: %s\n", optarg);  
  39.   
  40.             }   
  41.             break;   
  42.         case 'i':   
  43.             device = optarg;   
  44.             break;   
  45.         case 's':   
  46.             if (!(src_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  47.             {   
  48.                 libnet_error(LIBNET_ERR_FATAL,   
  49.                     "Bad source IP address: %s\n", optarg);   
  50.             }   
  51.             break;   
  52.         default:   
  53.             exit(EXIT_FAILURE);   
  54.         }   
  55.     }  
  56.   
  57.     if (!src_ip || !dst_ip)   
  58.     {   
  59.         usage(argv[0]);   
  60.         exit(EXIT_FAILURE);   
  61.     }  
  62.   
  63.     /*  
  64.     * Step 1: Network Initialization (interchangable with step 2).  
  65.     */   
  66.     if (device == NULL)   
  67.     {   
  68.         struct sockaddr_in sin;   
  69.         /*  
  70.         * Try to locate a device.  
  71.         */   
  72.         if (libnet_select_device(&sin, &device, err_buf) == -1)   
  73.         {   
  74.             libnet_error(LIBNET_ERR_FATAL,   
  75.                 "libnet_select_device failed: %s\n", err_buf);   
  76.         }   
  77.         printf("device:\t\t\t\t%s\n", device);   
  78.     }  
  79.   
  80.     if ((network = libnet_open_link_interface(device, err_buf)) == NULL)   
  81.     {   
  82.         libnet_error(LIBNET_ERR_FATAL,   
  83.             "libnet_open_link_interface: %s\n", err_buf);   
  84.     }  
  85.   
  86.     /*  
  87.     * We're going to build an ICMP packet with no payload using the  
  88.     * link-layer API, so this time we need memory for a ethernet header  
  89.     * as well as memory for the ICMP and IP headers.  
  90.     */   
  91.     packet_size = LIBNET_IP_H + LIBNET_ETH_H + LIBNET_ICMP_MASK_H;  
  92.   
  93.   
  94.     /*  
  95.     * Step 2: Memory Initialization (interchangable with step 1).  
  96.     */   
  97.     if (libnet_init_packet(packet_size, &packet) == -1)   
  98.     {   
  99.         libnet_error(LIBNET_ERR_FATAL, "libnet_init_packet failed\n");   
  100.     }  
  101.   
  102.   
  103.     /*  
  104.     * Step 3: Packet construction (ethernet header).  
  105.     */   
  106.     libnet_build_ethernet(enet_dst,   
  107.         enet_src,   
  108.         ETHERTYPE_IP,   
  109.         NULL,   
  110.         0,   
  111.         packet);  
  112.   
  113.     /*  
  114.     * Step 3: Packet construction (ICMP header).  
  115.     */   
  116.     libnet_build_icmp_mask(ICMP_MASKREPLY, /* type */   
  117.         0, /* code */   
  118.         242, /* id */   
  119.         0, /* seq */   
  120.         0xffffffff, /* mask */   
  121.         NULL, /* payload */   
  122.         0, /* payload_s */   
  123.         packet + LIBNET_ETH_H + LIBNET_IP_H);  
  124.   
  125.   
  126.     /*  
  127.     * Step 3: Packet construction (IP header).  
  128.     */   
  129.     libnet_build_ip(ICMP_MASK_H,   
  130.         0, /* IP tos */   
  131.         242, /* IP ID */   
  132.         0, /* Frag */   
  133.         64, /* TTL */   
  134.         IPPROTO_ICMP, /* Transport protocol */   
  135.         src_ip, /* Source IP */   
  136.         dst_ip, /* Destination IP */   
  137.         NULL, /* Pointer to payload (none) */   
  138.         0,   
  139.         packet + LIBNET_ETH_H); /* Packet header memory */  
  140.   
  141.     /*  
  142.     * Step 4: Packet checksums (ICMP header *AND* IP header).  
  143.     */   
  144.     if (libnet_do_checksum(packet + ETH_H, IPPROTO_ICMP, LIBNET_ICMP_MASK_H) == -1)   
  145.     {   
  146.         libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");   
  147.     }   
  148.     if (libnet_do_checksum(packet + ETH_H, IPPROTO_IP, LIBNET_IP_H) == -1)   
  149.     {   
  150.         libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");   
  151.     }  
  152.   
  153.   
  154.     /*  
  155.     * Step 5: Packet injection.  
  156.     */   
  157.     c = libnet_write_link_layer(network, device, packet, packet_size);   
  158.     if (c < packet_size)   
  159.     {   
  160.         libnet_error(LN_ERR_WARNING,   
  161.             "libnet_write_link_layer only wrote %d bytes\n", c);   
  162.     }   
  163.     else   
  164.     {   
  165.         printf("construction and injection completed, wrote all %d bytes\n", c);   
  166.     }  
  167.   
  168.   
  169.     /*  
  170.     * Shut down the interface.  
  171.     */   
  172.     if (libnet_close_link_interface(network) == -1)   
  173.     {   
  174.         libnet_error(LN_ERR_WARNING,   
  175.             "libnet_close_link_interface couldn't close the interface");   
  176.     }  
  177.   
  178.   
  179.     /*  
  180.     * Free packet memory.  
  181.     */   
  182.     libnet_destroy_packet(&packet);  
  183.   
  184.     return (c == -1 ? EXIT_FAILURE : EXIT_SUCCESS);   
  185. }  
  186.   
  187. void usage(char *name)   
  188. {   
  189.     fprintf(stderr, "usage: %s [-i interface] -s s_ip -d d_ip\n", name);   
  190. }  


例三:

  1. /* Example 3 [raw socket api - ICMP_ECHO using an arena] */  
  2. /* gcc -Wall `libnet-config --defines` libnet-example-x.c -o libnet-example-x \  
  3. `libnet-config --libs` */  
  4.   
  5. #include <libnet.h>  
  6.   
  7. void usage(char *);  
  8.   
  9.   
  10. int main(int argc, char **argv)   
  11. {   
  12.     int network, n, c, number_of_packets, packet_size;   
  13.     struct libnet_arena arena, *arena_p;   
  14.     u_char *packets[10];   
  15.     u_long src_ip, dst_ip;  
  16.   
  17.     printf("libnet example code:\tmodule 3\n\n");   
  18.     printf("packet injection interface:\tlink layer\n");   
  19.     printf("packet type:\t\t\tICMP_ECHO [no payload] using an arena\n");  
  20.   
  21.     src_ip = 0;   
  22.     dst_ip = 0;   
  23.     while((c = getopt(argc, argv, "d:s:")) != EOF)   
  24.     {   
  25.         switch (c)   
  26.         {   
  27.         case 'd':   
  28.             if (!(dst_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  29.             {   
  30.                 libnet_error(LIBNET_ERR_FATAL,   
  31.                     "Bad destination IP address: %s\n", optarg);   
  32.             }   
  33.             break;   
  34.         case 's':   
  35.             if (!(src_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  36.             {   
  37.                 libnet_error(LIBNET_ERR_FATAL,   
  38.                     "Bad source IP address: %s\n", optarg);   
  39.             }   
  40.             break;   
  41.         }   
  42.     }   
  43.     if (!src_ip || !dst_ip)   
  44.     {   
  45.         usage(argv[0]);   
  46.         exit(EXIT_FAILURE);   
  47.     }  
  48.   
  49.     /*  
  50.     * We're just going to build an ICMP packet with no payload using the  
  51.     * raw sockets API, so we only need memory for a ICMP header and an IP  
  52.     * header.  
  53.     */   
  54.     packet_size = LIBNET_IP_H + LIBNET_ICMP_ECHO_H;  
  55.   
  56.     /*  
  57.     * Let's just build say, 10 packets.  
  58.     */   
  59.     number_of_packets = 10;  
  60.   
  61.     arena_p = &arena;   
  62.     if (libnet_init_packet_arena(&arena_p, number_of_packets, packet_size) == -1)   
  63.     {   
  64.         libnet_error(LIBNET_ERR_FATAL, "libnet_init_packet_arena failed\n");   
  65.     }   
  66.     else   
  67.     {   
  68.         printf("Allocated an arena of %ld bytes..\n",   
  69.             LIBNET_GET_ARENA_SIZE(arena));   
  70.     }  
  71.   
  72.     network = libnet_open_raw_sock(IPPROTO_RAW);   
  73.     if (network == -1)   
  74.     {   
  75.         libnet_error(LIBNET_ERR_FATAL, "Can't open the network.\n");   
  76.     }  
  77.   
  78.     for (n = 0; n < number_of_packets; n++)   
  79.     {   
  80.         printf("%ld bytes remaining in arena\n",   
  81.             LIBNET_GET_ARENA_REMAINING_BYTES(arena));   
  82.         packets[n] = libnet_next_packet_from_arena(&arena_p, packet_size);   
  83.         if (!packets[n])   
  84.         {   
  85.             libnet_error(LIBNET_ERR_WARNING, "Arena is empty\n");   
  86.             continue;   
  87.         }  
  88.   
  89.         libnet_build_ip(ICMP_ECHO_H, /* Size of the payload */   
  90.             IPTOS_LOWDELAY | IPTOS_THROUGHPUT, /* IP tos */   
  91.             242, /* IP ID */   
  92.             0, /* frag stuff */   
  93.             48, /* TTL */   
  94.             IPPROTO_ICMP, /* transport protocol */   
  95.             src_ip, /* source IP */   
  96.             dst_ip, /* destination IP */   
  97.             NULL, /* pointer to payload */   
  98.             0, /* payload length */   
  99.             packets[n]); /* packet header memory */  
  100.   
  101.         libnet_build_icmp_echo(ICMP_ECHO, /* type */   
  102.             0, /* code */   
  103.             242, /* id */   
  104.             5, /* seq */   
  105.             NULL, /* pointer to payload */   
  106.             0, /* payload length */   
  107.             packets[n] + LIBNET_IP_H); /* packet header memory */  
  108.   
  109.         if (libnet_do_checksum(packets[n], IPPROTO_ICMP, LIBNET_ICMP_ECHO_H) == -1)   
  110.         {   
  111.             libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");   
  112.         }  
  113.   
  114.         c = libnet_write_ip(network, packets[n], packet_size);   
  115.         if (c < packet_size)   
  116.         {   
  117.             libnet_error(LN_ERR_WARNING,   
  118.                 "libnet_write_ip only wrote %d bytes\n", c);   
  119.         }   
  120.         else   
  121.         {   
  122.             printf("construction and injection of packet %d of %d completed, wrote all %d bytes\n",  
  123.                 n + 1, number_of_packets, c);   
  124.         }   
  125.     }  
  126.   
  127.     libnet_destroy_packet_arena(&arena_p);   
  128.     return (c == -1 ? EXIT_FAILURE : EXIT_SUCCESS);   
  129. }  
  130.   
  131.   
  132. void usage(char *name)   
  133. {   
  134.     fprintf(stderr, "usage: %s -s source_ip -d destination_ip\n ", name);   
  135. }  


例四:

  1. /* Example 4 [link-layer api - UDP packet using port list chaining] */  
  2. /* gcc -Wall `libnet-config --defines` libnet-example-x.c -o libnet-example-x \  
  3. `libnet-config --libs` */  
  4.   
  5. #include <libnet.h>  
  6.   
  7. #define MAX_PAYLOAD_SIZE 1024  
  8.   
  9. void usage(char *);  
  10.   
  11. u_char enet_src[6] = {0x0d, 0x0e, 0x0a, 0x0d, 0x00, 0x00};   
  12. u_char enet_dst[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};  
  13.   
  14. int main(int argc, char *argv[])   
  15. {   
  16.     int packet_size, /* size of our packet */   
  17.         payload_size, /* size of our packet */   
  18.         c; /* misc */   
  19.     u_long src_ip, dst_ip; /* source ip, dest ip */   
  20.     u_short bport, eport; /* beginning and end ports */   
  21.     u_short cport; /* current port */   
  22.     u_char payload[MAX_PAYLOAD_SIZE]; /* packet payload */   
  23.     u_char *packet; /* pointer to our packet buffer */   
  24.     char err_buf[LIBNET_ERRBUF_SIZE]; /* error buffer */   
  25.     u_char *device; /* pointer to the device to use */   
  26.     struct libnet_link_int *network; /* pointer to link interface struct */   
  27.     struct libnet_plist_chain plist; /* plist chain */   
  28.     struct libnet_plist_chain *plist_p; /* plist chain pointer */  
  29.   
  30.     printf("libnet example code:\tmodule 4\n\n");   
  31.     printf("packet injection interface:\tlink layer\n");   
  32.     printf("packet type:\t\t\tUDP [with payload] using port list chaining\n");  
  33.   
  34.     plist_p = NULL;   
  35.     device = NULL;   
  36.     src_ip = 0;   
  37.     dst_ip = 0;  
  38.   
  39.     while ((c = getopt(argc, argv, "i:d:s:p:")) != EOF)   
  40.     {   
  41.         switch (c)   
  42.         {   
  43.         case 'd':   
  44.             if (!(dst_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  45.             {   
  46.                 libnet_error(LIBNET_ERR_FATAL,   
  47.                     "Bad destination IP address: %s\n", optarg);  
  48.   
  49.             }   
  50.             break;   
  51.         case 'i':   
  52.             device = optarg;   
  53.             break;   
  54.         case 's':   
  55.             if (!(src_ip = libnet_name_resolve(optarg, LIBNET_RESOLVE)))   
  56.             {   
  57.                 libnet_error(LIBNET_ERR_FATAL,   
  58.                     "Bad source IP address: %s\n", optarg);   
  59.             }   
  60.             break;   
  61.         case 'p':   
  62.             plist_p = &plist;   
  63.             if (libnet_plist_chain_new(&plist_p, optarg) == -1)   
  64.             {   
  65.                 libnet_error(LIBNET_ERR_FATAL,   
  66.                     "Could not build port list\n");   
  67.             }   
  68.             break;   
  69.         default:   
  70.             usage(argv[0]);   
  71.             exit(EXIT_FAILURE);   
  72.         }   
  73.     }  
  74.   
  75.     if (!src_ip || !dst_ip || !plist_p)   
  76.     {   
  77.         usage(argv[0]);   
  78.         exit(EXIT_FAILURE);   
  79.     }  
  80.   
  81.     c = argc - optind;   
  82.     if (c != 1)   
  83.     {   
  84.         usage(argv[0]);   
  85.         exit(EXIT_FAILURE);   
  86.     }   
  87.     memset(payload, 0, sizeof(payload));   
  88.     strncpy(payload, argv[optind], strlen(argv[optind]));  
  89.   
  90.   
  91.     /*  
  92.     * Step 1: Network Initialization (interchangable with step 2).  
  93.     */   
  94.     if (device == NULL)   
  95.     {   
  96.         struct sockaddr_in sin;   
  97.         /*  
  98.         * Try to locate a device.  
  99.         */   
  100.         if (libnet_select_device(&sin, &device, err_buf) == -1)   
  101.         {   
  102.             libnet_error(LIBNET_ERR_FATAL,   
  103.                 "libnet_select_device failed: %s\n", err_buf);   
  104.         }   
  105.         printf("device:\t\t\t\t%s\n", device);   
  106.     }   
  107.     if ((network = libnet_open_link_interface(device, err_buf)) == NULL)   
  108.     {   
  109.         libnet_error(LIBNET_ERR_FATAL,   
  110.             "libnet_open_link_interface: %s\n", err_buf);   
  111.     }  
  112.   
  113.     /*  
  114.     * Get the payload from the user. Hrm. This might fail on a Sparc  
  115.     * if byte alignment is off...  
  116.     */   
  117.     payload_size = strlen(payload);  
  118.   
  119.     /*  
  120.     * We're going to build a UDP packet with a payload using the  
  121.     * link-layer API, so this time we need memory for a ethernet header  
  122.     * as well as memory for the ICMP and IP headers and our payload.  
  123.     */   
  124.     packet_size = LIBNET_IP_H + LIBNET_ETH_H + LIBNET_UDP_H + payload_size;  
  125.   
  126.     /*  
  127.     * Step 2: Memory Initialization (interchangable with step 1).  
  128.     */   
  129.     if (libnet_init_packet(packet_size, &packet) == -1)   
  130.     {   
  131.         libnet_error(LIBNET_ERR_FATAL, "libnet_init_packet failed\n");   
  132.     }  
  133.   
  134.   
  135.     /*  
  136.     * Step 3: Packet construction (ethernet header).  
  137.     */   
  138.     libnet_build_ethernet(enet_dst,   
  139.         enet_src,   
  140.         ETHERTYPE_IP,   
  141.         NULL,   
  142.         0,   
  143.         packet);  
  144.   
  145.     /*  
  146.     * Step 3: Packet construction (IP header).  
  147.     */   
  148.     libnet_build_ip(LIBNET_UDP_H + payload_size,   
  149.         0, /* IP tos */   
  150.         242, /* IP ID */   
  151.         0, /* Frag */   
  152.         64, /* TTL */   
  153.         IPPROTO_UDP, /* Transport protocol */   
  154.         src_ip, /* Source IP */   
  155.         dst_ip, /* Destination IP */   
  156.         NULL, /* Pointer to payload (none) */   
  157.         0,   
  158.         packet + LIBNET_ETH_H); /* Packet header memory */  
  159.   
  160.     while (libnet_plist_chain_next_pair(plist_p, &bport, &eport))   
  161.     {  
  162.   
  163.         while (!(bport > eport) && bport != 0)   
  164.         {   
  165.             cport = bport++;   
  166.             /*  
  167.             * Step 3: Packet construction (UDP header).  
  168.             */   
  169.             libnet_build_udp(242, /* source port */   
  170.                 cport, /* dest. port */   
  171.                 payload, /* payload */   
  172.                 payload_size, /* payload length */   
  173.                 packet + LIBNET_ETH_H + LIBNET_IP_H);  
  174.   
  175.             /*  
  176.             * Step 4: Packet checksums (ICMP header *AND* IP header).  
  177.             */   
  178.             if (libnet_do_checksum(packet + ETH_H, IPPROTO_UDP, LIBNET_UDP_H + payload_size) == -1)   
  179.             {   
  180.                 libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");   
  181.             }   
  182.             if (libnet_do_checksum(packet + ETH_H, IPPROTO_IP, LIBNET_IP_H) == -1)   
  183.             {   
  184.                 libnet_error(LIBNET_ERR_FATAL, "libnet_do_checksum failed\n");   
  185.             }  
  186.   
  187.             /*  
  188.             * Step 5: Packet injection.  
  189.             */   
  190.             c = libnet_write_link_layer(network, device, packet, packet_size);   
  191.             if (c < packet_size)   
  192.             {   
  193.                 libnet_error(LN_ERR_WARNING,   
  194.                     "libnet_write_link_layer only wrote %d bytes\n", c);   
  195.             }   
  196.             else   
  197.             {   
  198.                 printf("construction and injection completed, wrote all %d bytes, port %d\n",  
  199.                     c, cport);   
  200.             }   
  201.         }   
  202.     }   
  203.     /*  
  204.     * Shut down the interface.  
  205.     */   
  206.     if (libnet_close_link_interface(network) == -1)   
  207.     {   
  208.         libnet_error(LN_ERR_WARNING,   
  209.             "libnet_close_link_interface couldn't close the interface");   
  210.     }  
  211.   
  212.   
  213.     /*  
  214.     * Free packet memory.  
  215.     */   
  216.     libnet_destroy_packet(&packet);  
  217.   
  218.     return (c == -1 ? EXIT_FAILURE : EXIT_SUCCESS);   
  219. }  
  220.   
  221.   
  222. void usage(char *name)   
  223. {   
  224.     fprintf(stderr, "usage: %s [-i interface] -s s_ip -d d_ip -p port list payload\n", name);   
  225. }   


 例五:

  1. 給出一個綜合應用libnet和libpcap的簡單例程,其功能是在接收到一個來自特定主機的ARP請求報文之後,發出ARP迴應報文,通知該主機請求的IP地址對應的MAC地址。這個程序實現了標準的ARP協議,但是卻不同於操作系統內核中標準的實現方法:該程序利用了libpcap在數據鏈路層抓包,利用了libnet向數據鏈路層發包,是使用libnet和libpcap構造TCP/IP協議軟件的一個例程。該程序很簡單,但已經可以說明libnet和libpcap的綜合使用方法:  
  2.   
  3. /* tell destination host with ip 'dstip' that the host with  
  4. * request ip 'srcip' is with mac address srcmac 
  5. * author: white cpf  2003.5.15. 
  6. * compile: gcc arp.c -lnet -lpcap -o arp 
  7. */  
  8. #include "/usr/include/libnet.h"  
  9. #include <pcap.h>  
  10. void usage(char * exename){  
  11.     printf(" tell dstip with dstmac that srcip is at srcmac. \n");  
  12.     printf(" usage: %s -d dstip -s srcip -D dstmac -S srcmac \n",exename);  
  13.     return ;  
  14. }  
  15. //程序輸入:來自命令行參數  
  16. u_char ip_src[4],ip_dst[4];  
  17. u_char enet_src[6],enet_dst[6];  
  18. extern int mac_strtochar6(u_char * enet,char * macstr);  
  19. //將字符串格式的MAC地址轉換爲6字節類型r  
  20. int get_cmdline(int argc,char *argv[]);//命令行參數處理函數  
  21. int main(int argc, char *argv[]){  
  22.     libnet_t *l;  
  23.     libnet_ptag_t t;  
  24.     u_char *packet;  
  25.     u_long packet_s;  
  26.     char device[5]="eth0";  
  27.     char errbuf[LIBNET_ERRBUF_SIZE];  
  28.     char filter_str[100]="";  
  29.     struct bpf_program fp;      /* hold compiled program     */  
  30.     char *dev;  
  31.     pcap_t* descr;  
  32.     struct pcap_pkthdr hdr;     /* pcap.h    */  
  33.     u_char * packet;  
  34.     bpf_u_int32 maskp;          /* subnet mask               */  
  35.     bpf_u_int32 netp;           /* ip                        */  
  36.     int promisc=0;               /* set to promisc mode?        */  
  37.     int pcap_time_out=5;  
  38.     int c, ret;  
  39.     u_long i;  
  40.     if(get_cmdline(argc,argv)<=0){  
  41.         usage(argv[0]);  
  42.         exit(0);  
  43.     }  
  44.   
  45.     dev = pcap_lookupdev(errbuf);  
  46.     if(dev == NULL){   
  47.         fprintf(stderr,"%s\n",errbuf);  
  48.         return -1;  
  49.     }  
  50.     ret=pcap_lookupnet(dev,&netp,&maskp,errbuf);  
  51.     if(ret==-1){  
  52.         fprintf(stderr,"%s\n",errbuf);  
  53.         return -1;  
  54.     }  
  55.     descr = pcap_open_live(dev,BUFSIZ,promisc,pcap_time_out,errbuf);  
  56.     if(descr == NULL){  
  57.         printf("pcap_open_live(): %s\n",errbuf);  
  58.         return -1;   
  59.     }  
  60.     sprintf(filter_str,"arp and (src net %d.%d.%d.%d)",ip_dst[0],ip_dst[1],  
  61.         ip_dst[2],ip_dst[3]);  
  62.     if(pcap_compile(descr,&fp,filter_str,0,netp) == -1){  
  63.         printf("Error calling pcap_compile\n");   
  64.         return -1;  
  65.     }  
  66.     if(pcap_setfilter(descr,&fp) == -1){   
  67.         printf("Error setting filter\n");   
  68.         return -1;  
  69.     }  
  70.     while(1){  
  71.         printf("wait packet:filter:%s\n",filter_str);  
  72.         packet=pcap_next(descr, &hdr);  
  73.         if(packet == NULL){  
  74.             continue;  
  75.         }  
  76.         l = libnet_init(LIBNET_LINK_ADV,device,errbuf);   
  77.         if (l == NULL){  
  78.             fprintf(stderr, "libnet_init() failed: %s", errbuf);  
  79.             exit(EXIT_FAILURE);  
  80.         }  
  81.         t = libnet_build_arp(  
  82.             ARPHRD_ETHER,                           /* hardware addr */  
  83.             ETHERTYPE_IP,                           /* protocol addr */  
  84.             6,                                      /* hardware addr size */  
  85.             4,                                      /* protocol addr size */  
  86.             ARPOP_REPLY,                            /* operation type */  
  87.             enet_src,                               /* sender hardware addr */  
  88.             ip_src,                           /* sender protocol addr */  
  89.             enet_dst,                               /* target hardware addr */  
  90.             ip_dst,                           /* target protocol addr */  
  91.             NULL,                                   /* payload */  
  92.             0,                                      /* payload size */  
  93.             l,                                      /* libnet handle */  
  94.             0);                                     /* libnet id */  
  95.         if (t == -1){  
  96.             fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l));  
  97.             goto bad;  
  98.         }  
  99.         t = libnet_autobuild_ethernet(  
  100.             enet_dst,                               /* ethernet destination */  
  101.             ETHERTYPE_ARP,                          /* protocol type */  
  102.             l);                                     /* libnet handle */  
  103.         if (t == -1){  
  104.             fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l));  
  105.             goto bad;  
  106.         }  
  107.         c = libnet_adv_cull_packet(l, &packet, &packet_s);  
  108.         if (c == -1){  
  109.             fprintf(stderr, "libnet_adv_cull_packet: %s\n", libnet_geterror(l));  
  110.             goto bad;  
  111.         }  
  112.         c = libnet_write(l);  
  113.         if (c == -1){  
  114.             fprintf(stderr, "Write error: %s\n", libnet_geterror(l));  
  115.             goto bad;  
  116.         }  
  117.         continue;  
  118. bad:  
  119.         libnet_destroy(l);  
  120.         return (EXIT_FAILURE);  
  121.     }  
  122.     libnet_destroy(l);  
  123.     return (EXIT_FAILURE);  
  124. }  
  125. int get_cmdline(int argc,char *argv[]){  
  126.     char c;  
  127.     char string[]="d:s:D:S:h";  
  128.     while((c = getopt(argc, argv, string)) != EOF){  
  129.         if(c=='d')  
  130.             *((unsigned int*)ip_dst)=(unsigned int)inet_addr(optarg);  
  131.         else if(c== 's')  
  132.             *((unsigned int*)ip_src)=(unsigned int)inet_addr(optarg);  
  133.         else if(c=='D')  
  134.             mac_strtochar6(enet_dst,optarg);  
  135.         else if(c=='S')  
  136.             mac_strtochar6(enet_dst,optarg);  
  137.         else if(c=='h')  
  138.             return 0;  
  139.         else  
  140.             return -1;  
  141.     }  
  142.     return 1;  
  143. }  


 例六:

  1. #include <win32/libnet.h>  
  2. #pragma comment(lib, "libnet.lib")  
  3.   
  4. void main()  
  5. {  
  6.     int packet_size;//存放數據包長度的變量  
  7.     libnet_t *l;//libnet句柄  
  8.     libnet_ptag_t protocol_tag;//協議塊標記  
  9.     char *device = NULL;//設備名字,此時爲NULL  
  10.     char error_information[LIBNET_ERRBUF_SIZE];//用來存放錯誤信息  
  11.     char *destination_ip_str = "192.168.0.2";//目的IP地址字符串變量,可以指定任意一個合法的IP地址  
  12.     char *source_ip_str = "192.168.0.3";//源IP地址字符串變量,可以指定任意一個合法的IP地址  
  13.   
  14.     u_char hardware_source[6] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06};//源MAC地址,可以是任意指定  
  15.     u_char hardware_destination[6] ={0x06, 0x05, 0x04, 0x03, 0x02, 0x01};//目的MAC地址,可以是任意指定  
  16.   
  17.     u_long destination_ip;// 目的IP地址  
  18.     u_long source_ip;//源IP地址  
  19.   
  20.     l = libnet_init(  
  21.         LIBNET_LINK_ADV,//libnet類型 */  
  22.         device,//網絡設備  
  23.         error_information);   
  24.   
  25.     destination_ip = libnet_name2addr4(l,destination_ip_str, LIBNET_RESOLVE);  
  26.     //把目的IP地址字符串形式轉化成網絡順序字節形式的數據  
  27.     source_ip = libnet_name2addr4(l, source_ip_str, LIBNET_RESOLVE);  
  28.     //把源IP地址字符串形式轉化成網絡順序字節形式的數據  
  29.   
  30.     protocol_tag = libnet_build_arp(  
  31.         //構造ARP協議塊,函數的返回值是代表新生成的ARP協議塊的一個協議塊標記  
  32.         ARPHRD_ETHER,  
  33.         // 硬件地址類型,在這裏是以太網  
  34.         ETHERTYPE_IP,  
  35.         //協議地址類型,在這裏是IP協議  
  36.         6,  
  37.         //硬件地址長度,MAC地址的長度爲6  
  38.         4,  
  39.         //協議地址長度,IP地址的長度爲4  
  40.         ARPOP_REPLY,  
  41.         //操作類型,在這裏是ARP應答類型  
  42.         hardware_source,  
  43.         //源硬件地址  
  44.         (u_int8_t*) &source_ip,  
  45.         //源IP地址  
  46.         hardware_destination,  
  47.         //目標硬件地址  
  48.         (u_int8_t*) &destination_ip,  
  49.         //目標協議地址  
  50.         NULL,  
  51.         //負載,此時爲NULL  
  52.         0,  
  53.         //負載的長度,此時爲0  
  54.         l,  
  55.         //libnet句柄,此句柄由libnet_init()函數生成  
  56.         0  
  57.         //協議塊標記,此時爲0,表示構造一個新的ARP協議塊,而不是修改已經存在的協議塊  
  58.         );  
  59.   
  60.     protocol_tag = libnet_autobuild_ethernet(  
  61.         // 以auto的形式構造一個以太網協議塊,返回一個指向此協議塊的標記  
  62.         hardware_destination,  
  63.         //目的硬件地址  
  64.         ETHERTYPE_ARP,  
  65.         //以太網上層協議類型,此時爲ARP類型  
  66.         l //libnet句柄  
  67.         );  
  68.   
  69.     packet_size = libnet_write(l);//發送已經構造的ARP數據包  
  70.     printf("發送一個%d字節長度的ARP應答數據包 ", packet_size);//輸出發送的ARP數據包的字節數  
  71.   
  72.     libnet_destroy(l);//銷燬libnet  
  73. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章