使用Wireshark测试手机APP网络通信完整指南
环境准备和配置
网络拓扑
手机设备 (APP) → WiFi路由器 → 电脑 (运行Wireshark)
工具准备
# 安装Wireshark
# Windows: 从官网下载安装包
# Mac: brew install wireshark
# Linux: sudo apt-get install wireshark
# 安装adb工具(Android调试)
brew install android-platform-tools # Mac
# 或下载Android Studio包含的adb
手机流量捕获方法
WiFi网络捕获(推荐)
设置电脑为热点
# Windows - 创建热点
netsh wlan set hostednetwork mode=allow ssid=MyHotspot key=MyPassword123
netsh wlan start hostednetwork# Mac - 使用内置互联网共享
# 系统偏好设置 → 共享 → 互联网共享
Wireshark配置
打开Wireshark,选择热点对应的网络接口
设置捕获过滤器减少干扰
# 只捕获手机IP的流量
host 192.168.173.100# 或捕获特定协议
tcp port 80 or tcp port 443 or tcp port 8080
方法二:USB网络共享捕获
Android设备设置
# 启用USB调试
adb devices # 验证设备连接# 设置端口转发
adb forward tcp:5555 tcp:5555# 使用tcpdump在手机上捕获(需要root)
adb shell
tcpdump -i any -s 0 -w /sdcard/capture.pcap
从手机拉取捕获文件
adb pull /sdcard/capture.pcap ./mobile_capture.pcap
方法三:路由器端口镜像
支持端口镜像的路由器配置
# 不同路由器命令不同,示例如下:
# 将手机流量镜像到电脑连接的端口
configure terminal
monitor session 1 source interface Wi-Fi0
monitor session 1 destination interface GigabitEthernet0/1
Wireshark过滤器和分析技巧
常用显示过滤器
# 按IP地址过滤
ip.addr == 192.168.1.100
!(ip.addr == 192.168.1.100) # 排除特定IP# 按协议过滤
http or http2 or tls
dns # DNS查询分析# 按端口过滤
tcp.port == 8080
tcp.port == 443# 组合过滤器
http and ip.src == 192.168.1.100
tls.handshake.type == 1 # Client Hello# 应用层过滤
http.request.method == "POST"
http contains "login"
http.response.code == 200
特定APP流量识别
# 通过User-Agent识别
http.user_agent contains "MyApp"# 通过Host识别
http.host contains "api.myapp.com"# 通过自定义头部识别
http.header contains "X-App-Version"
性能测试和分析
网络延迟分析
# 过滤TCP握手过程
tcp.flags.syn == 1 or tcp.flags.ack == 1# 查看TCP流时序
# 右键 → Follow → TCP Stream
带宽使用分析
# 统计流量使用
Statistics → Conversations → IPv4# 查看流量趋势
Statistics → I/O Graph
自定义性能指标
-- 创建自定义列显示响应时间
-- Edit → Preferences → Appearance → Columns
-- 添加新列,使用字段:tcp.time_delta
APP启动性能测试
# 捕获过滤器
host 192.168.1.100 and (tcp port 80 or tcp port 443)# 测试步骤:
1. 清空Wireshark捕获
2. 关闭APP后台进程
3. 开始捕获
4. 启动APP
5. 等待首屏完全加载
6. 停止捕获
API请求分析
# 分析脚本示例 - 提取API性能数据
import pyshark
import jsondef analyze_api_performance(pcap_file):cap = pyshark.FileCapture(pcap_file, display_filter='http')api_metrics = []for packet in cap:try:if hasattr(packet, 'http'):http_layer = packet.httpmetric = {'timestamp': float(packet.sniff_timestamp),'method': getattr(http_layer, 'request_method', 'N/A'),'uri': getattr(http_layer, 'request_uri', 'N/A'),'host': getattr(http_layer, 'host', 'N/A'),'response_code': getattr(http_layer, 'response_code', 'N/A'),'length': int(packet.length)}api_metrics.append(metric)except AttributeError:continue# 计算性能指标analyze_metrics(api_metrics)def analyze_metrics(metrics):total_requests = len(metrics)successful_requests = len([m for m in metrics if m['response_code'] == '200'])print(f"总请求数: {total_requests}")print(f"成功请求: {successful_requests}")print(f"成功率: {(successful_requests/total_requests)*100:.2f}%")# 使用示例
analyze_api_performance('mobile_capture.pcap')
安全测试
# 检查明文传输
http and !(http.host contains "localhost")# 检查弱加密
tls.handshake.type == 2 and (ssl.handshake.ciphersuites contains "0x0005" or ssl.handshake.ciphersuites contains "0x0004")# 检查证书有效性
tls.handshake.certificate
使用tshark命令行分析
#!/bin/bash
# automated_mobile_test.sh# 开始捕获
tshark -i en0 -f "host 192.168.1.100" -w mobile_capture.pcap &# 执行APP测试场景
echo "开始APP测试..."
# 这里可以集成Appium或其他自动化测试框架# 等待测试完成
sleep 60# 停止捕获
pkill -f tshark# 分析结果
echo "分析网络流量..."
tshark -r mobile_capture.pcap -Y "http" -T fields \-e frame.time_relative \-e http.request.method \-e http.request.uri \-e http.response.code \> http_analysis.csvecho "测试完成,结果保存到 http_analysis.csv"
Python自动化分析
import subprocess
import time
import pandas as pd
from datetime import datetimeclass MobileNetworkAnalyzer:def __init__(self, device_ip, interface='en0'):self.device_ip = device_ipself.interface = interfaceself.capture_file = f"capture_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pcap"def start_capture(self):"""开始网络捕获"""cmd = ['tshark', '-i', self.interface,'-f', f'host {self.device_ip}','-w', self.capture_file]self.capture_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)print(f"开始捕获流量到 {self.capture_file}")def stop_capture(self):"""停止捕获"""self.capture_process.terminate()self.capture_process.wait()print("捕获已停止")def analyze_performance(self):"""分析性能指标"""# HTTP请求分析http_cmd = ['tshark', '-r', self.capture_file,'-Y', 'http','-T', 'fields','-e', 'frame.time_relative','-e', 'http.request.method','-e', 'http.request.uri','-e', 'http.response.code','-e', 'http.content_length']result = subprocess.run(http_cmd, capture_output=True, text=True)http_data = []for line in result.stdout.strip().split('\n'):if line:parts = line.split('\t')if len(parts) >= 4:http_data.append({'timestamp': float(parts[0]),'method': parts[1],'uri': parts[2],'status_code': parts[3],'content_length': parts[4] if len(parts) > 4 else '0'})return pd.DataFrame(http_data)def generate_report(self, df):"""生成性能报告"""report = {'total_requests': len(df),'successful_requests': len(df[df['status_code'] == '200']),'failed_requests': len(df[df['status_code'] != '200']),'avg_response_size': df['content_length'].astype(float).mean(),'test_duration': df['timestamp'].max() if not df.empty else 0}print("=== 网络性能测试报告 ===")print(f"总请求数: {report['total_requests']}")print(f"成功请求: {report['successful_requests']}")print(f"失败请求: {report['failed_requests']}")print(f"成功率: {(report['successful_requests']/report['total_requests'])*100:.2f}%")print(f"平均响应大小: {report['avg_response_size']:.2f} bytes")print(f"测试时长: {report['test_duration']:.2f} 秒")return report# 使用示例
if __name__ == "__main__":analyzer = MobileNetworkAnalyzer('192.168.1.100')try:analyzer.start_capture()time.sleep(60) # 运行测试60秒finally:analyzer.stop_capture()df = analyzer.analyze_performance()report = analyzer.generate_report(df)
精彩推荐:点击蓝字即可
▲软件负载测试 ▲API自动化测试 ▲软件测试 ▲第三方软件测试 ▲软件性能测试 ▲软件测试机构