|Network| How to monitor the network traffic of the specific application

If we want to write a service in the Android framework, how can we do ?
There are some things we should know before starting to implement.
– what is UID in Android ? what’s different with Linux UID ?
– what is the relationship between UID and PID ?
– how can we use libpcap for Applications in the embedded system ?

This article will answer those questions and point out a direction.

Overview:
Android framework | Linux space | Network stack |
An UID for an app <—–> maybe PIDs <—> Socket IP & Port

  • What is UID in Android ? what’s different with Linux UID ?
    UID := user ID (UID) is particular to each Android application.
    Each Android package (.apk) installed will be given an unique Linux user ID, creating a kernel-level Application Sandbox.

    Ref. https://stackoverflow.com/questions/5708906/what-is-uid-on-android
  • How can we get UID ?
    – If you implement App or Framework service, using:
    PackageManager and getApplicationInfo().
    – If you want to use adb for testing purpose, using
    adb shell dumpsys package {package name} | grep userId=
    e.g. adb shell dumpsys package com.android.phone | grep userId=
    It will show an number larger than 10000. (UID >= 10000)
    Ref. https://blog.csdn.net/zhao007z5/article/details/79973752

  • What is the relationship between UID and PID ?
    UID is user ID.
    PID is process ID.
    One UID may have multiple PIDs.

    Get PID:
    adb shell pidof -s {package name}

    More information:
    adb shell cat /proc/{pid}/status
  • How can we use libpcap for Applications in the embedded system ?
    If you want to use tcpdump,
    – find the local address of socket, netstat -tup or ss -tup
    tcpdump -i wlan0 src <IP> and port <PORT>

    If you want to use Iptables,
    – find PIDs of APP.
    – iptables -I OUTPUT -m owner –uid-owner -j LOG –log-level 7 –log-prefix ‘SNIFFER: ‘ –log-uid

    If you want to use netstat,
    – netstat -np –inet | grep “package name”


    Ref.
    netstat: https://unix.stackexchange.com/questions/375387/how-to-trace-networking-activity-of-a-command
    How to view network traffic requested by a specific app?