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


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

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

lookup() ->

opendevice(_Interface) ->

capture() ->

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

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" {

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


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;
        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);

    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");
        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++)
  [i] = packet[i];
        bin.size = sizeof("NULL"); = "NULL";
    return enif_make_binary(env, &bin);

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


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").

([email protected])2> c(nif).

([email protected])3> nif:lookup().

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



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:// 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 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 package tcpdump-i eth1 host / tmp / xxx.cap Grasping 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: 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: # 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