Skip to content

Instantly share code, notes, and snippets.

@angad
Created May 17, 2011 17:48
Show Gist options
  • Save angad/976962 to your computer and use it in GitHub Desktop.
Save angad/976962 to your computer and use it in GitHub Desktop.

##libpcap for Android

###Android.mk

LOCAL_PATH := ./jni  

include $(CLEAR_VARS)  
LOCAL_MODULE    := pcaptest  
LOCAL_SRC_FILES := libpcap-native.c  

LOCAL_C_INCLUDES := $(NDK_ROOT)/external/libpcap   

LOCAL_STATIC_LIBRARIES := libpcap  

LOCAL_LDLIBS := -ldl -llog  

include $(BUILD_SHARED_LIBRARY)   

include $(NDK_ROOT)/external/libpcap/Android.mk  

Libpcap for android is built as a static library and its functions are then used as a shared library.
A shared library build specifications are defined in the Android.mk make file in the JNI folder of the project. The JNI folder maintains contains the make files for the library. It also contains the native C code with function definitions according to the Java package.

This is a sample JNI code for getting the list of available network interfaces by using the pcap_lookupdevs function

#include <jni.h>  
#include <string.h>  
#include <android/log.h>  
#include <pcap.h>  

#define DEBUG_TAG "Sample_LIBPCAP_DEBUGGING"  

void Java_org_umit_android_libpcaptest_libpcaptest_testLog(JNIEnv *env, jclass clazz, jstring message)  
{  
    char errbuf[1024];  
    errbuf[0] = '\0';  

   	char *szLogThis;  
	char *dev = pcap_lookupdev(errbuf);  

    if (dev == NULL) {  
	    szLogThis = "Couldn't find default device";		  
	}  
    else szLogThis = dev;  

	__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "Device status: [%s]", szLogThis);  
	__android_log_print(ANDROID_LOG_DEBUG, DEBUG_TAG, "errbuf [%s]", errbuf);  

	(*env)->ReleaseStringUTFChars(env, message, szLogThis);  
}  

The C code can now be called as native functions from inside Java code by loading the shared library

static{  
    System.loadLibrary("pcaptest");  
}  

private native void testLog(String logThis);  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment