Use Erlang NIF to snoop, capture packets (in Windows XP)

2010-02-03  来源:本站原创  分类:Tech  人气:305 

1. Overview

In my last blog topic, I realize a network sniffer in Ubuntu, here I rewrite the code in Windows XP, and add a new function to find all network adapter.

2. Developing enviroment

- Windows xp

- MinGW 5.1.6

- Gcc 3.4.5

- WinPcap 4.1.1

- Erlang / OTP R13B03

3. Nif.erl

%%% nif sniffer

-module(nif).
-on_load(on_load/0).

-export([lookup/0, opendevice/1, capture/0, loop/1]).

on_load() ->
    ok = erlang:load_nif("./nif", 0),
    true.

lookup() ->
    error.

opendevice(_Interface) ->
    error.

capture() ->
    error.

loop(0) ->
    ok;
loop(Count) ->
    Pkt = capture(),
    io:format("~p~n", [Pkt]),
    loop(Count-1).

4. Nif.h

#include "erl_nif.h"
#include "stdio.h"
#include "pcap.h"
#include "string.h"
#include "ctype.h"

#ifndef NIF_H
#define NIF_H

#ifdef __cplusplus
extern "C" {
#endif

static ERL_NIF_TERM opendevice(ErlNifEnv* env, ERL_NIF_TERM device);
static ERL_NIF_TERM capture(ErlNifEnv* env);
static ERL_NIF_TERM lookup(ErlNifEnv* env);

#ifdef __cplusplus
}
#endif

#endif

5. Nif.c

/* This file used to create a Erlang NIF which sniffer network packets. */
#include "nif.h"

pcap_t *devHandler = NULL;

static int my_enif_get_string(ErlNifEnv *env, ERL_NIF_TERM list, char* buf)
{
    ERL_NIF_TERM cell, head, tail;
    int val;

    while (enif_get_list_cell(env, list, &head, &tail))
    {
        if (!enif_get_int(env, head, &val)) return 1;
        *buf = (char)val;
        buf++;
        list = tail;
    }
    *buf = '\0';
    return 0;
}

static ERL_NIF_TERM lookup(ErlNifEnv* env)
{
    int i = 0;
    char errbuf[PCAP_ERRBUF_SIZE], str[1024];
    pcap_if_t *alldevs;
    pcap_if_t *d;

    if (pcap_findalldevs_ex("rpcap://", NULL /* auth is not needed */, &alldevs, errbuf) == -1)
        return enif_make_string(env, errbuf);

    for(d= alldevs; d != NULL; d= d->next)
    {
        strcat(str, d->name);
        strcat(str, "|||");

    /*
        strcat(str, "\t\t");
        if (d->description)
            strcat(str, d->description);
        else
            strcat(str,"\n");
    */
    }

    pcap_freealldevs(alldevs);
    return enif_make_string(env, str);
}

static ERL_NIF_TERM opendevice(ErlNifEnv* env, ERL_NIF_TERM device)
{
    char dev[64];
    char errbuf[PCAP_ERRBUF_SIZE];

    //memset(errbuf, 0, PCAP_ERRBUF_SIZE);
    my_enif_get_string(env, device, dev);
    /* return enif_make_string(env, dev); */

    /* Parms: dev,snaplen,promisc,timeout_ms,errbuf
     * to_ms=0 means wait enough packet to arrive.
     */
    devHandler = pcap_open_live(dev, 65535, 1, 0, errbuf);
    if(devHandler != NULL)
        return enif_make_atom(env, "ok");
    else
        return enif_make_string(env, errbuf);
}

static ERL_NIF_TERM capture(ErlNifEnv* env)
{
    int i;
    struct pcap_pkthdr pkthdr;
    const u_char *packet = NULL;
    ErlNifBinary bin;

    packet = pcap_next(devHandler, &pkthdr);
    if(packet != NULL)
    {
        enif_alloc_binary(env, pkthdr.len, &bin);
        for(i = 0; i < pkthdr.len; i++)
        {
            bin.data[i] = packet[i];
        }
    }
    else
    {
        bin.size = sizeof("NULL");
        bin.data = "NULL";
    }
    return enif_make_binary(env, &bin);
}

static ErlNifFunc nif_funcs[] =
{
    {"lookup", 0, lookup},
    {"capture", 0, capture},
    {"opendevice", 1, opendevice}
};

ERL_NIF_INIT(nif,nif_funcs,NULL,NULL,NULL,NULL)

6. Build the code

- Insatll minGW, and re-set% PATH%,% C_INCLUDE_PATH%,% LIBRARY_PATH%.

- Copy the ERTS WinPcap include and lib folder to minGW folder.

- Copy wpcap.lib to source folder.

- In windows [cmd] enviroment, execute following

gcc -shared -o nif.dll nif.c wpcap.lib

7. Test the code

Erlang R13B03 (erts-5.7.4) [smp:2:2] [rq:2] [async-threads:0]

Eshell V5.7.4  (abort with ^G)
([email protected])1> cd("sniffer_nif/win32").
D:/workspace/sniffer_nif/win32
ok

([email protected])2> c(nif).
{ok,nif}

([email protected])3> nif:lookup().
"rpcap://\\Device\\NPF_GenericDialupAdapter|||
rpcap://\\Device\\NPF_{CB6CFA59-46DE-4172-BBB1-85C85E654848}
|||rpcap://\\Device\\NPF_{B9A5FCD5-1424-4F42-B680-E73A89CFF638}|||"

([email protected])4> nif:opendevice("rpcap://\\Device\\NPF_{CB6CFA59-46DE-4172-BBB1-85C85E654848}").
ok

--------------------------------------------------------------

<<255,255,255,255,255,255,0,27,185,223,71,97,8,0,69,0,0,78,188,123,0,0,128,17,
  13,12,10,184,45,169,10,184,45,255,0,137,0,137,0,58,111,159,134,52,1,16,0,1,0,
  0,0,0,0,0,32,69,75,69,74,69,66,69,79,69,76,69,80,69,79,69,72,69,67,69,66,69,
  79,67,65,67,65,67,65,67,65,67,65,0,0,32,0,1>>
<<255,255,255,255,255,255,0,35,77,220,61,143,8,0,69,0,0,78,19,248,0,0,64,17,
  245,76,10,184,45,236,10,184,45,255,0,137,0,137,0,58,191,137,128,20,1,16,0,1,
  0,0,0,0,0,0,32,69,70,69,73,70,65,70,65,67,65,67,65,67,65,67,65,67,65,67,65,
  67,65,67,65,67,65,67,65,67,65,66,76,0,0,32,0,1>>
<<1,128,194,0,0,0,0,2,125,41,137,65,0,38,66,66,3,0,0,0,0,0,128,0,0,2,125,41,
  137,64,0,0,0,0,128,0,0,2,125,41,137,64,10,13,0,0,20,0,2,0,15,0,0,0,0,0,0,0,0,
  0>>
<<255,255,255,255,255,255,0,35,84,32,248,213,8,6,0,1,8,0,6,4,0,1,0,35,84,32,
  248,213,10,184,45,230,0,0,0,0,0,0,10,184,45,136,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0>>
 。。。

8. Note

- I tried the visuall c + + 6.0, failed, the cl tool are so old.

- After call [nif: lookup ()] function, there are 3 net adapter with register style output, very strange.

相关文章
  • Use Erlang NIF to snoop, capture packets (in Windows XP) 2010-02-03

    1. Overview In my last blog topic, I realize a network sniffer in Ubuntu, here I rewrite the code in Windows XP, and add a new function to find all network adapter. 2. Developing enviroment - Windows xp - MinGW 5.1.6 - Gcc 3.4.5 - WinPcap 4.1.1 - Erl

  • Use Erlang NIF to snoop, capture packets (in Windows XP), in OTP-R13B04 2010-02-26

    1. Introduction Http://xumingyong.javaeye.com/blog/586743 last blog post, I am in Erlang/OTP-R13B03, the use of the network packet nif realized grasping function, but due to R13B04 version, NIF form interface, occurred change (see next paragraph summ

  • Can't compile erlang NIF library on macos? 2010-12-03

    I try to write and test an erlang-NIF library, all things going to be ok on linux, but when I try this on my MBP, I got an error below: gcc *.c -fPIC -dynamiclib -o mynif.so Undefined symbols: "_enif_is_atom", referenced from: _mynif_func in ccS

  • wifi capture packets 2015-01-09

    1. iw dev wlan0 interface add mon_wlan0 type monitor 2. ifconfig mon_wlan0 up 3. iwconfig mon_wlan0 channel 'X' 4. wireshark base on mon_wlan0 Ps: check channel support or not with command "iwlist wlan0 channel" tshark -r capture_packets_0.pcap

  • solaris snoop own packet capture tools 2010-07-14

    In solaris may be ordered through the system comes with snoop packet capture. Common format: snoop-x0 host [hostip] Monitor and [hostip] communication packets. snoop-x0-d bge0 host [hostip] Monitor LAN equipment [bge0] and [hostip] communication pack

  • Macos compiled in 64-bit erlang and nif 2010-12-03

    Solve the following issues today: macos compiled dynamic link library problem macos lead NIF database architecture under the code the problem can not be loaded Re-macos compiled under 64-bit version of erlang Until not get compiled in macos nif probl

  • In Java using Jpcap capture network packet [reproduced] 2010-03-29

    In Java using network packet capture Jpcap If you want to capture the network packets in Java programs, then you need some support tools, because the core Java API can not access the underlying network data. But Jpcap is a Windows or UNIX systems pro

  • simple case of the command tcpdump packet capture 2010-04-13

    tcpdump to capture packets saved to file with the command parameter is-w xxx.cap Eth1 packets grasp tcpdump-i eth1-w / tmp / xxx.cap Grasping 192.168.1.123 package tcpdump-i eth1 host 192.168.1.123-w / tmp / xxx.cap Grasping 192.168.1.123 port 80 pac

  • Linux packet capture tools: TCPDUMP Introduction 2010-08-17

    About TCPDUMP For the network management personnel, the uses Sniffer is available at any time of Web actual situation Zai Wang Luo performance dramatically come down, you can Tongguo sniffer tool to Fenxiyuanyin what contributed to the network conges

  • Small scale NIF (on) 2010-09-26

    NIF is the Erlang OTP R13B03 version introduced in this version is only an experimental feature, according to the original plan, NIF in R14B version of a formal nature, the corresponding API will also be stabilized in the later version. Can not wait,

  • High-speed network based on the zero-copy packet capture mechanism 2010-10-19

    See also: http://www.linuxjournal.com/article/6345 http://www.ibm.com/developerworks/cn/java/j-zerocopy/index.html http://blog.chinaunix.net/u/5251/showart_411109.html 1. The traditional realization of packet capture 1.1 Operating Mechanism of the st

  • Java network packet capture and analysis of JPcap procedures (multi-protocol analysis, knowledge networks for beginners who have a good network to help) [Z] 2010-12-29

    This program is the use of JPcap package, crawl through the local network card data frame, and analysis procedures for each field. This is one of my online course design, specific training in the following report describes in detail about, along with

  • tcpdump packet capture analysis of TCP three-way handshake 2011-03-22

    A, tcpdump uses 1, first look MAN Manual TCPDUMP (8) NAME tcpdump - dump traffic on a network SYNOPSIS tcpdump [-AdDeflLnNOpqRStuUvxX] [-c count] [-C file_size] [-F file] [-I interface] [-m module] [-M secret] [-R file] [-s snaplen] [-T type] [-w fil

  • winpcap packet capture 2011-07-28

    / / Technical Manual: http://www.ferrisxu.com/WinPcap/html/index.html # Include "stdafx.h" # Include <iostream> using namespace std; # Include <pcap.h> / * int _tmain (int argc, _TCHAR * argv []) { pcap_if_t * allAdapters; / / the li

  • tcpdump capture small details 2011-10-05

    Today in the use of tcpdump to capture, then use wireshark to analyze the time, there has been "Packet size limited during capture", is not considered an error, but data can not fully view the contents of the bag clearly: After a query, because

  • Chapter VI erlang programming compile and run 2010-10-11

    Compile and run the translator: gashero Directory ? A start and stop the Erlang shell ? 2 modify the development environment ? 2.1 set the search path of loader code ? 2.2 in the system startup sequence of commands ? 3 other ways to run the program ?

  • Linux system does not respond to SYN packets solution 2011-08-22

    Syn Why did not respond on the issue is really depressed for a long time. Phenomenon is the issue of syn packets on the client when the server's syn packet to the client without any response. Shopping online shopping, finally found some people have s

  • 5.编译并运行erlang程序 2012-02-29

    1.停止erlang系统方法: ctrl+C(Windows下 ctrl+Break). 不可控关闭BIF函数: erlang:halt() 强制停止系统(小瑕疵:对于大型的数据库操作程序,可能在下次需要进行一些回复操作) 可控关闭:q().该函数是init:stop()在shell中的简写,该操作会做一些清除和关闭操作,保证系统正确关闭 2.为文件加载器设定加载路径 code:get_path(). 获得当前设定的文件加载路径列表 @spec code:add_patha(Dir) 增加新目录

  • [转载]Syntax Highlighing for Erlang in NotePad++ 2013-01-05

    Update: The definition has been updated to include support for atoms, variables and function names as well as additional file extensions. Screen shot and downloadable content have been updated. Thus far I've done all of my Erlang development on Fedor

  • UNIX-depth analysis of network protocol 2010-07-15

    Introduction Network is already ubiquitous, and many times we will use the network to communicate with different hosts, including internal and external networks. In most cases this will not be a problem, but sometimes you need to double-check your ne