活动介绍
file-type

TCP与UDP数据包编程:Windows平台下开发实战

版权申诉

RAR文件

15KB | 更新于2024-11-13 | 31 浏览量 | 0 下载量 举报 收藏
download 限时特惠:#14.90
本资源的标签为‘tcp_packet_ udp_packet’,表明其内容围绕着两种主要的网络传输层协议——传输控制协议(TCP)和用户数据报协议(UDP)。文件压缩包内包含了程序的源代码,文件名称列表中只有一个项‘Code’,这可能意味着压缩包内包含了所有源代码文件。" 知识点详细说明: 1. **TCP (传输控制协议)**: - TCP是面向连接的、可靠的、基于字节流的传输层通信协议。 - 它通过序列号、确认应答、超时重传等机制保证了数据的可靠传输。 - 在Windows XP SP2环境下,TCP编程允许开发者创建能够处理数据的完整性和顺序的网络应用程序。 - 使用*** 2003,开发者可以利用C#或***等编程语言创建TCP客户端和服务器。 - TCP的三次握手和四次挥手过程是确保连接正确建立和终止的关键步骤。 - TCP协议是互联网中应用最为广泛的协议之一,它支持HTTP、FTP、SMTP等多种应用层协议。 2. **UDP (用户数据报协议)**: - UDP是一种无连接的网络协议,提供了一种无需建立连接即可发送数据的方式。 - UDP不保证数据包的顺序、可靠性或完整性,但因其简单和低延迟的特点,在需要快速传输大量数据的应用中非常有用。 -UDP通常用于视频流、音频流或实时游戏等领域,这些应用可以容忍数据包丢失,但对延迟敏感。 - 在Windows平台上开发UDP程序时,开发者需要处理数据包的接收和发送,但不需处理连接管理。 *** 2003提供了相应的网络编程接口,可以用来开发处理UDP数据包的应用程序。 3. **网络编程基础**: - 网络编程是指编写能够在网络上进行通信的软件。 - 编程时需要对协议栈、套接字编程和网络地址转换等有深入的理解。 - 套接字(Socket)是网络通信的端点,通过IP地址和端口号标识。 - 在Windows环境下,Winsock API是进行网络通信的主要接口。 - 网络编程的一个核心任务是实现数据的序列化和反序列化,确保数据在发送端和接收端之间正确传输。 4. *** 2003**: *** 2003是微软公司开发的一个集成开发环境(IDE),专门用于.NET应用程序的开发。 - 它支持多种编程语言,包括C#、***等,允许开发者进行高效的网络编程。 - 该IDE提供了丰富的工具和组件,简化了Windows编程和网络编程的过程。 - 开发者可以通过*** 2003创建、调试和部署TCP和UDP程序。 - 该环境还支持版本控制和团队协作,有助于多人项目开发。 5. **文件压缩和解压**: - ‘TCP-and-UDP-packet-program-.rar’文件是一个压缩包,使用了RAR格式进行压缩。 - 压缩文件通常用于减少文件大小和将多个文件打包成一个便于传输。 - 解压缩工具如WinRAR或7-Zip可以用来打开和提取RAR文件中的内容。 - 压缩包内包含了一个名为'Code'的文件夹,表明原始的源代码文件已经被压缩在一起。 总结:提供的文件资源主要涉及网络编程领域中的TCP和UDP数据包的发送和处理程序的开发。开发者利用Windows XP SP2平台和*** 2003环境创建了这些程序,它们使用了TCP和UDP协议来实现数据传输。资源标签明确指出内容与TCP数据包和UDP数据包有关,压缩包内的文件名称表明了代码的存在,但未提供具体的代码文件列表。此资源对于学习和深入理解网络编程以及TCP和UDP协议的应用具有一定的价值。

相关推荐

filetype

import numpy as np from matplotlib import pyplot as plt import scapy.all as scapy from collections import defaultdict from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score import pandas as pd # ====================== # 1. PCAP文件解析与流重组 # ====================== print("正在解析PCAP文件...") packets = scapy.rdpcap('test.pcap') # 按五元组重组网络流 flows = defaultdict(list) for pkt in packets: if 'IP' in pkt: # 获取协议类型 (TCP=6, UDP=17, ICMP=1) proto = pkt['IP'].proto src_port = pkt[proto].sport if proto in pkt else 0 dst_port = pkt[proto].dport if proto in pkt else 0 # 创建流标识键 (源IP, 目的IP, 源端口, 目的端口, 协议) flow_key = (pkt['IP'].src, pkt['IP'].dst, src_port, dst_port, proto) flows[flow_key].append(pkt) print(f"共识别出 {len(flows)} 个网络流") # ====================== # 2. 特征工程 # ====================== print("正在提取流量特征...") features = [] valid_flows = [] for flow_key, packets in flows.items(): # 跳过包含少于5个包的流 if len(packets) < 5: continue # 基础统计特征 packet_count = len(packets) total_bytes = sum(len(p) for p in packets) # 时序特征 timestamps = [float(p.time) for p in packets] # 关键修改:转换为float iat = np.diff(timestamps) # 包间隔时间 mean_iat = np.mean(iat) if len(iat) > 0 else 0 std_iat = np.std(iat) if len(iat) > 1 else 0 # 包长特征 pkt_lengths = [len(p) for p in packets] mean_pkt_len = np.mean(pkt_lengths) std_pkt_len = np.std(pkt_lengths) min_pkt_len = min(pkt_lengths) max_pkt_len = max(pkt_lengths) # 方向特征 (0=客户端到服务器, 1=服务器到客户端) directions = [1 if p['IP'].src == flow_key[0] else 0 for p in packets] up_ratio = sum(directions) / len(directions) features.append([ packet_count, total_bytes, mean_iat, std_iat, mean_pkt_len, std_pkt_len, min_pkt_len, max_pkt_len, up_ratio ]) valid_flows.append(flow_key) # 转换为特征矩阵 feature_matrix = np.array(features) feature_names = [ '包数量', '总字节数', '平均包间隔', '包间隔标准差', '平均包长', '包长标准差', '最小包长', '最大包长', '上行比例' ] print(f"提取了 {len(features)} 个有效流的 {len(feature_names)} 维特征") # ====================== # 3. 数据标准化 # ====================== print("正在进行数据标准化...") scaler = StandardScaler() scaled_features = scaler.fit_transform(feature_matrix) # ====================== # 4. 肘部法则确定最佳K值 # ====================== print("使用肘部法则确定最佳聚类数...") n_samples = scaled_features.shape[0] # 获取实际样本数 # 根据样本数量动态调整K范围 if n_samples < 5: print(f"警告:样本数量较少({n_samples}),将使用简化聚类策略") k_range = range(1, min(11, n_samples + 1)) # K值上限不超过样本数 else: k_range = range(1, 11) # 测试1-10个聚类 sse = [] kmeans_models = {} # 存储每个K的模型 for k in k_range: # 确保K值不超过样本数 if k > n_samples: print(f"跳过K={k}(超过样本数{n_samples})") continue kmeans = KMeans(n_clusters=k, n_init=10, random_state=42) kmeans.fit(scaled_features) sse.append(kmeans.inertia_) # 获取SSE kmeans_models[k] = kmeans # 存储模型 # 如果没有足够的点绘制肘部图,直接选择K值 if len(sse) < 2: optimal_k = min(2, n_samples) # 至少2类,但不超过样本数 print(f"样本过少,直接设置K={optimal_k}") else: # 绘制肘部法则图 plt.figure(figsize=(10, 6)) plt.plot(list(k_range)[:len(sse)], sse, 'bo-') plt.xlabel('聚类数量 $ K$') plt.ylabel('SSE (误差平方和)') plt.title('肘部法则确定最佳聚类数') plt.grid(True) plt.savefig('elbow_method.png', dpi=300) plt.close() print("肘部法则图已保存为 elbow_method.png") # 自动检测拐点 (肘点) if len(sse) >= 3: # 至少有3个点才能计算二阶差分 knee_point = np.argmin(np.diff(sse, 2)) + 2 optimal_k = max(2, min(10, knee_point)) # 确保在2-10之间 else: # 样本较少时使用简单策略 optimal_k = max(2, min(3, n_samples)) # 选择2或3 print(f"自动检测的最佳聚类数: K = {optimal_k}") # ====================== # 5. K-means聚类 # ====================== print(f"正在进行K-means聚类 (K={optimal_k})...") # 如果样本数小于K,调整K值 if optimal_k > n_samples: optimal_k = max(1, n_samples) # 确保K不超过样本数 print(f"调整聚类数为样本数: K = {optimal_k}") # 使用之前存储的模型或创建新模型 if optimal_k in kmeans_models: kmeans = kmeans_models[optimal_k] cluster_labels = kmeans.labels_ else: kmeans = KMeans(n_clusters=optimal_k, n_init=10, random_state=42) cluster_labels = kmeans.fit_predict(scaled_features) # 计算轮廓系数(仅当K>1时) if optimal_k > 1: silhouette_avg = silhouette_score(scaled_features, cluster_labels) print(f"轮廓系数: {silhouette_avg:.4f} (接近1表示聚类效果良好)") else: print("聚类数为1,无需计算轮廓系数") # ====================== # 6. 结果分析与可视化 # ====================== # 创建结果DataFrame result_df = pd.DataFrame({ '源IP': [flow[0] for flow in valid_flows], '目的IP': [flow[1] for flow in valid_flows], '协议': [f"TCP(6)" if flow[4] == 6 else f"UDP(17)" for flow in valid_flows], '聚类标签': cluster_labels }) # 添加特征值到结果表 for i, name in enumerate(feature_names): result_df[name] = feature_matrix[:, i] # 保存聚类结果 result_df.to_csv('cluster_results.csv', index=False) print("聚类结果已保存为 cluster_results.csv") # 各簇统计信息 cluster_stats = result_df.groupby('聚类标签').agg({ '包数量': 'mean', '总字节数': 'mean', '平均包间隔': 'mean', '上行比例': 'mean' }).rename(columns={ '包数量': '平均包数量', '总字节数': '平均总字节数', '平均包间隔': '平均包间隔(s)', '上行比例': '平均上行比例' }) print("\n各用户簇流量特征统计:") print(cluster_stats.round(2)) # 可视化聚类结果 (使用前两个主成分) from sklearn.decomposition import PCA pca = PCA(n_components=2) principal_components = pca.fit_transform(scaled_features) plt.figure(figsize=(12, 8)) scatter = plt.scatter( principal_components[:, 0], principal_components[:, 1], c=cluster_labels, cmap='viridis', alpha=0.6 ) # 添加簇中心 centers = pca.transform(kmeans.cluster_centers_) plt.scatter( centers[:, 0], centers[:, 1], c='red', s=200, alpha=0.9, marker='X', edgecolor='black' ) plt.colorbar(scatter, label='用户簇') plt.xlabel('主成分 1') plt.ylabel('主成分 2') plt.title(f'校园网用户流量聚类 (K={optimal_k})') plt.grid(alpha=0.3) plt.savefig('cluster_visualization.png', dpi=300) plt.close() print("聚类可视化图已保存为 cluster_visualization.png") print("\n聚类完成! 结果文件已保存:") print("- elbow_method.png: 肘部法则图") print("- cluster_results.csv: 详细聚类结果") print("- cluster_visualization.png: 聚类可视化") 编译结果如下,解释一下编译结果 E:\用户画像\聚类分离用户数据\.venv\Scripts\python.exe E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py 正在解析PCAP文件... 共识别出 3 个网络流 正在提取流量特征... 提取了 3 个有效流的 9 维特征 正在进行数据标准化... 使用肘部法则确定最佳聚类数... 警告:样本数量较少(3),将使用简化聚类策略 E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 35823 (\N{CJK UNIFIED IDEOGRAPH-8BEF}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 24046 (\N{CJK UNIFIED IDEOGRAPH-5DEE}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 24179 (\N{CJK UNIFIED IDEOGRAPH-5E73}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 26041 (\N{CJK UNIFIED IDEOGRAPH-65B9}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 21644 (\N{CJK UNIFIED IDEOGRAPH-548C}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 32920 (\N{CJK UNIFIED IDEOGRAPH-8098}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 37096 (\N{CJK UNIFIED IDEOGRAPH-90E8}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 27861 (\N{CJK UNIFIED IDEOGRAPH-6CD5}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 21017 (\N{CJK UNIFIED IDEOGRAPH-5219}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 30830 (\N{CJK UNIFIED IDEOGRAPH-786E}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 23450 (\N{CJK UNIFIED IDEOGRAPH-5B9A}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 26368 (\N{CJK UNIFIED IDEOGRAPH-6700}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 20339 (\N{CJK UNIFIED IDEOGRAPH-4F73}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 32858 (\N{CJK UNIFIED IDEOGRAPH-805A}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 31867 (\N{CJK UNIFIED IDEOGRAPH-7C7B}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:132: UserWarning: Glyph 25968 (\N{CJK UNIFIED IDEOGRAPH-6570}) missing from font(s) DejaVu Sans. plt.savefig('elbow_method.png', dpi=300) Font 'default' does not have a glyph for '\u805a' [U+805a], substituting with a dummy symbol. Font 'default' does not have a glyph for '\u7c7b' [U+7c7b], substituting with a dummy symbol. Font 'default' does not have a glyph for '\u6570' [U+6570], substituting with a dummy symbol. Font 'default' does not have a glyph for '\u91cf' [U+91cf], substituting with a dummy symbol. C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 35823 (\N{CJK UNIFIED IDEOGRAPH-8BEF}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 24046 (\N{CJK UNIFIED IDEOGRAPH-5DEE}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 24179 (\N{CJK UNIFIED IDEOGRAPH-5E73}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 26041 (\N{CJK UNIFIED IDEOGRAPH-65B9}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 21644 (\N{CJK UNIFIED IDEOGRAPH-548C}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 32920 (\N{CJK UNIFIED IDEOGRAPH-8098}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 37096 (\N{CJK UNIFIED IDEOGRAPH-90E8}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 27861 (\N{CJK UNIFIED IDEOGRAPH-6CD5}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 21017 (\N{CJK UNIFIED IDEOGRAPH-5219}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 30830 (\N{CJK UNIFIED IDEOGRAPH-786E}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 23450 (\N{CJK UNIFIED IDEOGRAPH-5B9A}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 26368 (\N{CJK UNIFIED IDEOGRAPH-6700}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 20339 (\N{CJK UNIFIED IDEOGRAPH-4F73}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 32858 (\N{CJK UNIFIED IDEOGRAPH-805A}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 31867 (\N{CJK UNIFIED IDEOGRAPH-7C7B}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 25968 (\N{CJK UNIFIED IDEOGRAPH-6570}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) Font 'default' does not have a glyph for '\u805a' [U+805a], substituting with a dummy symbol. Font 'default' does not have a glyph for '\u7c7b' [U+7c7b], substituting with a dummy symbol. Font 'default' does not have a glyph for '\u6570' [U+6570], substituting with a dummy symbol. Font 'default' does not have a glyph for '\u91cf' [U+91cf], substituting with a dummy symbol. 肘部法则图已保存为 elbow_method.png 自动检测的最佳聚类数: K = 2 正在进行K-means聚类 (K=2)... 轮廓系数: 0.1744 (接近1表示聚类效果良好) 聚类结果已保存为 cluster_results.csv 各用户簇流量特征统计: 平均包数量 平均总字节数 平均包间隔(s) 平均上行比例 聚类标签 0 10.5 3721.0 0.04 1.0 1 6.0 1023.0 0.16 1.0 E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 20027 (\N{CJK UNIFIED IDEOGRAPH-4E3B}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 25104 (\N{CJK UNIFIED IDEOGRAPH-6210}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 20998 (\N{CJK UNIFIED IDEOGRAPH-5206}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 26657 (\N{CJK UNIFIED IDEOGRAPH-6821}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 22253 (\N{CJK UNIFIED IDEOGRAPH-56ED}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 32593 (\N{CJK UNIFIED IDEOGRAPH-7F51}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 29992 (\N{CJK UNIFIED IDEOGRAPH-7528}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 25143 (\N{CJK UNIFIED IDEOGRAPH-6237}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 27969 (\N{CJK UNIFIED IDEOGRAPH-6D41}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 37327 (\N{CJK UNIFIED IDEOGRAPH-91CF}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 32858 (\N{CJK UNIFIED IDEOGRAPH-805A}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 31867 (\N{CJK UNIFIED IDEOGRAPH-7C7B}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) E:\用户画像\聚类分离用户数据\聚类分离校园网数据.py:234: UserWarning: Glyph 31751 (\N{CJK UNIFIED IDEOGRAPH-7C07}) missing from font(s) DejaVu Sans. plt.savefig('cluster_visualization.png', dpi=300) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 20027 (\N{CJK UNIFIED IDEOGRAPH-4E3B}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 25104 (\N{CJK UNIFIED IDEOGRAPH-6210}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 20998 (\N{CJK UNIFIED IDEOGRAPH-5206}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 26657 (\N{CJK UNIFIED IDEOGRAPH-6821}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 22253 (\N{CJK UNIFIED IDEOGRAPH-56ED}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 32593 (\N{CJK UNIFIED IDEOGRAPH-7F51}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 29992 (\N{CJK UNIFIED IDEOGRAPH-7528}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 25143 (\N{CJK UNIFIED IDEOGRAPH-6237}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 27969 (\N{CJK UNIFIED IDEOGRAPH-6D41}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 37327 (\N{CJK UNIFIED IDEOGRAPH-91CF}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 32858 (\N{CJK UNIFIED IDEOGRAPH-805A}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 31867 (\N{CJK UNIFIED IDEOGRAPH-7C7B}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) C:\Program Files\JetBrains\PyCharm 2025.1.2\plugins\python-ce\helpers\pycharm_matplotlib_backend\backend_interagg.py:124: UserWarning: Glyph 31751 (\N{CJK UNIFIED IDEOGRAPH-7C07}) missing from font(s) DejaVu Sans. FigureCanvasAgg.draw(self) 聚类可视化图已保存为 cluster_visualization.png 聚类完成! 结果文件已保存: - elbow_method.png: 肘部法则图 - cluster_results.csv: 详细聚类结果 - cluster_visualization.png: 聚类可视化 进程已结束,退出代码为 0

filetype

/************************************************************************** * simpletun.c * * * * A simplistic, simple-minded, naive tunnelling program using tun/tap * * interfaces and TCP. DO NOT USE THIS PROGRAM FOR SERIOUS PURPOSES. * * * * You have been warned. * * * * (C) 2010 Davide Brini. * * * * DISCLAIMER AND WARNING: this is all work in progress. The code is * * ugly, the algorithms are naive, error checking and input validation * * are very basic, and of course there can be bugs. If that's not enough, * * the program has not been thoroughly tested, so it might even fail at * * the few simple things it should be supposed to do right. * * Needless to say, I take no responsibility whatsoever for what the * * program might do. The program has been written mostly for learning * * purposes, and can be used in the hope that is useful, but everything * * is to be taken "as is" and without any kind of warranty, implicit or * * explicit. See the file LICENSE for further details. * *************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <net/if.h> #include <linux/if_tun.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <fcntl.h> #include <arpa/inet.h> #include <sys/select.h> #include <sys/time.h> #include <errno.h> #include <stdarg.h> #include <pthread.h> /* buffer for reading from tun/tap interface, must be >= 1500 */ #define BUFSIZE 200000 #define CLIENT 0 #define SERVER 1 #define PORT 55555 #define FILEOUT 1 int debug; char *progname; int recv_control_flag, type, value, tap2netInterval = 50; int net_fd; struct sockaddr_in dst_addr; /************************************************************************** * tun_alloc: allocates or reconnects to a tun/tap device. The caller * * must reserve enough space in *dev. * **************************************************************************/ int tun_alloc(char *dev, int flags) { struct ifreq ifr; int fd, err; char *clonedev = "/dev/net/tun"; if( (fd = open(clonedev , O_RDWR)) < 0 ) { perror("Opening /dev/net/tun"); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = flags; if (*dev) { strncpy(ifr.ifr_name, dev, IFNAMSIZ); } if( (err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0 ) { perror("ioctl(TUNSETIFF)"); close(fd); return err; } strcpy(dev, ifr.ifr_name); return fd; } /************************************************************************** * cread: read routine that checks for errors and exits if an error is * * returned. * **************************************************************************/ int cread(int fd, char *buf, int n){ int nread; if((nread=read(fd, buf, n)) < 0){ perror("Reading data"); exit(1); } return nread; } /************************************************************************** * cwrite: write routine that checks for errors and exits if an error is * * returned. * **************************************************************************/ int cwrite(int fd, char *buf, int n){ int nwrite; if((nwrite=write(fd, buf, n)) < 0){ perror("Writing data"); exit(1); } return nwrite; } /************************************************************************** * read_n: ensures we read exactly n bytes, and puts them into "buf". * * (unless EOF, of course) * **************************************************************************/ int read_n(int fd, char *buf, int n) { int nread, left = n; while(left > 0) { if ((nread = cread(fd, buf, left)) == 0){ return 0 ; }else { left -= nread; buf += nread; } } return n; } /************************************************************************** * do_debug: prints debugging stuff (doh!) * **************************************************************************/ void do_debug(char *msg, ...){ va_list argp; if(debug) { va_start(argp, msg); vfprintf(stderr, msg, argp); va_end(argp); } } /************************************************************************** * my_err: prints custom error messages on stderr. * **************************************************************************/ void my_err(char *msg, ...) { va_list argp; va_start(argp, msg); vfprintf(stderr, msg, argp); va_end(argp); } /************************************************************************** * usage: prints usage and exits. * **************************************************************************/ void usage(void) { fprintf(stderr, "Usage:\n"); fprintf(stderr, "%s -i <ifacename> [-s|-c <serverIP>] [-p <port>] [-u|-a] [-d]\n", progname); fprintf(stderr, "%s -h\n", progname); fprintf(stderr, "\n"); fprintf(stderr, "-i <ifacename>: Name of interface to use (mandatory)\n"); fprintf(stderr, "-s|-c <serverIP>: run in server mode (-s), or specify server address (-c <serverIP>) (mandatory)\n"); fprintf(stderr, "-p <port>: port to listen on (if run in server mode) or to connect to (in client mode), default 55555\n"); fprintf(stderr, "-u|-a: use TUN (-u, default) or TAP (-a)\n"); fprintf(stderr, "-d: outputs debug information while running\n"); fprintf(stderr, "-m: tun or tap ip address\n"); fprintf(stderr, "-h: prints this help text\n"); exit(1); } void *recv_control(void *para) { int cfd = socket(AF_INET, SOCK_DGRAM, 0); if (cfd < 0) { perror("socket error"); exit(1); } struct sockaddr_in serv; struct sockaddr_in clientsock; bzero(&serv, sizeof(serv)); serv.sin_family = AF_INET; serv.sin_port = htons(12366); serv.sin_addr.s_addr = htonl(INADDR_ANY); bind(cfd, (struct sockaddr *)&serv, sizeof(serv)); int i; int n; socklen_t len; uint32_t buf[100]; while (1) { memset(buf, 0x00, sizeof(buf)); len = sizeof(clientsock); n = recvfrom(cfd, buf, sizeof(buf), 0, (struct sockaddr *)&clientsock, &len); for (int i = 0; i < n; i++) { do_debug("%d ", buf[i]); } do_debug("\n"); if ((buf[0] == 0xffffffff) && (buf[1] == 1 || buf[1] == 2) && (buf[2] >= 1 && buf[2] <= 3)) { recv_control_flag = 1; type = buf[1]; value = buf[2]; int32_t control_message[3]; if (type == 2) { control_message[0] = 0xAAAAAAAA; if (value == 1) { tap2netInterval = 50; } else if (value == 2) { tap2netInterval = 250; } int len = sendto(net_fd, control_message, 4, 0, (struct sockaddr *)&dst_addr, sizeof(dst_addr)); do_debug("send reset message len : %d\n", len); sleep(7); } control_message[0] = 0xFFFFFFFF; control_message[1] = type; control_message[2] = value; int len = sendto(net_fd, control_message, 12, 0, (struct sockaddr *)&dst_addr, sizeof(dst_addr)); do_debug("send handout message len : %d\n", len); } else { printf("receive syntax error\n"); } sleep(1); } close(cfd); } int main(int argc, char *argv[]) { int tap_fd, option; int flags = IFF_TUN; char if_name[IFNAMSIZ] = ""; int maxfd; uint32_t nread, nwrite, plength; char buffer[BUFSIZE]; struct sockaddr_in local, remote; char remote_ip[16] = ""; /* dotted quad IP string */ char local_ip[16] = ""; char if_ipaddress[20] =""; unsigned short int port = PORT; unsigned short int rm_port = PORT; int sock_fd, optval = 1; socklen_t remotelen; int cliserv = -1; /* must be specified on cmd line */ unsigned long int tap2net = 0, net2tap = 0; char *Mode[2] = {"tun", "tap"}; int mode = 0; int connected_flag = 0; recv_control_flag = 0; progname = argv[0]; /* Check command line options */ while((option = getopt(argc, argv, "i:s:c:p:r:uahdm:")) > 0) { switch(option) { case 'd': debug = 1; break; case 'h': usage(); break; case 'i': strncpy(if_name,optarg, IFNAMSIZ-1); break; case 's': cliserv = SERVER; strncpy(remote_ip,optarg,15); break; case 'c': cliserv = CLIENT; strncpy(local_ip,optarg,15); break; case 'p': port = atoi(optarg); break; case 'r': rm_port = atoi(optarg); break; case 'u': flags = IFF_TUN; break; case 'a': flags = IFF_TAP; mode = 1; break; case 'm': strncpy(if_ipaddress,optarg,20); break; default: my_err("Unknown option %c\n", option); usage(); } } argv += optind; argc -= optind; if(argc > 0) { my_err("Too many options!\n"); usage(); } if(*if_name == '\0') { my_err("Must specify interface name!\n"); usage(); } else if(cliserv < 0) { my_err("Must specify client or server mode!\n"); usage(); } else if((cliserv == CLIENT)&&(*remote_ip == '\0')) { my_err("Must specify server address!\n"); usage(); } #if 0 char *gnb = "gnb.txt"; char *ue = "ue.txt"; FILE *gnb_fd, *ue_fd; gnb_fd = fopen(gnb, "w"); ue_fd = fopen(ue, "w"); if (gnb_fd == NULL || ue_fd == NULL) { fprintf(stderr, "can't open file\n"); return 1; } #endif char cmd[256]; snprintf(cmd, sizeof(cmd), "sudo ip tuntap del %s mode tap",if_name); system(cmd); snprintf(cmd, sizeof(cmd), "sudo ip tuntap del %s mode tun",if_name); system(cmd); if(*if_ipaddress != '\0'){ // char *if_ipaddress = "6.6.6.1/24"; snprintf(cmd, sizeof(cmd), "sudo ip tuntap add %s mode %s",if_name, Mode[mode]); system(cmd); snprintf(cmd, sizeof(cmd), "sudo ip addr add %s dev %s", if_ipaddress,if_name); system(cmd); snprintf(cmd, sizeof(cmd), "sudo ip link set dev %s up", if_name); system(cmd); char *remote_tun = (char *)malloc(sizeof(if_ipaddress)); memcpy(remote_tun, if_ipaddress, sizeof(if_ipaddress)); char *lastDot = strrchr(remote_tun, '.'); // int lastOctet = atoi(lastDot + 1); sprintf(lastDot + 1, "0/24"); do_debug("remote_tun ip: %s\n", remote_tun); snprintf(cmd, sizeof(cmd), "sudo ip route add %s dev %s", remote_tun, if_name); system(cmd); } // printf("pass\n"); /* initialize tun/tap interface */ if ( (tap_fd = tun_alloc(if_name, flags | IFF_NO_PI)) < 0 ) { my_err("Error connecting to tun/tap interface %s!\n", if_name); exit(1); } do_debug("Successfully connected to interface %s ip address %s\n", if_name, if_ipaddress); /*while(1){ nread = cread(tap_fd, buffer, BUFSIZE); tap2net++; do_debug("TAP2NET %lu: Read %d bytes from the tap interface\n", tap2net, nread); }*/ pthread_t pthread_recv = 0; int recv_flag = pthread_create(&pthread_recv, NULL, &recv_control, NULL); if (recv_flag != 0) { printf("create control_input failed\n"); } if ( (sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket()"); exit(1); } // 第二步:绑定地址(IP + Port) struct sockaddr_in myaddr; myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = inet_addr(local_ip); myaddr.sin_port = htons(port); if(bind(sock_fd, (struct sockaddr*)&myaddr, sizeof(myaddr)) == -1) { perror("bind"); return 1; } // 第三步:收发数据 // 发送数�? // 指定接收方地址 dst_addr.sin_family = AF_INET; dst_addr.sin_addr.s_addr = inet_addr(remote_ip);//命令行输入接收方IP dst_addr.sin_port = htons(rm_port);//命令行输入端口号 net_fd = sock_fd; /* use select() to handle two descriptors at once */ maxfd = (tap_fd > net_fd)?tap_fd:net_fd; socklen_t len = sizeof(struct sockaddr_in); struct sockaddr_in serveraddr; while(1) { int ret; fd_set rd_set; FD_ZERO(&rd_set); FD_SET(tap_fd, &rd_set); FD_SET(net_fd, &rd_set); ret = select(maxfd + 1, &rd_set, NULL, NULL, NULL); if (ret < 0 && errno == EINTR){ continue; } if (ret < 0) { perror("select()"); exit(1); } if(FD_ISSET(tap_fd, &rd_set)) { /* data from tun/tap: just read it and write it to the network */ usleep(tap2netInterval); nread = cread(tap_fd, buffer, BUFSIZE); if ((buffer[0]&0xf0)>>4 == 6) continue; tap2net++; do_debug("TAP2NET %lu: Read %d bytes from the tap interface\n", tap2net, nread); /* write length + packet */ //plength = htons(nread); //nwrite = cwrite(net_fd, (char *)&plength, sizeof(plength)); //nwrite = cwrite(net_fd, buffer, nread); sendto(net_fd, buffer, nread, 0, (struct sockaddr *)&dst_addr, sizeof(dst_addr)); do_debug("TAP2NET %lu: Written %d bytes to the network\n", tap2net, nread); #if 1 do_debug("TAP2NET %lu: ", tap2net); for (int i = 0; i < nread; i++){ // if (buffer[i] != 0) // fprintf(gnb_fd, "%02hhx ", buffer[i]); do_debug("%02hhx ", buffer[i]); } //fprintf(gnb_fd, "\n"); do_debug("\n"); #endif } if(FD_ISSET(net_fd, &rd_set)) { /* data from the network: read it, and write it to the tun/tap interface. * We need to read the length first, and then the packet */ /* Read length */ //nread = read_n(net_fd, (char *)&plength, sizeof(plength)); // nread = read_n(net_fd, buffer, BUFSIZE);//ntohs(plength)); remotelen = sizeof(dst_addr); nread = recvfrom(net_fd, buffer, BUFSIZE, 0, (struct sockaddr *)&dst_addr, &remotelen); do_debug("recv:%d\n", nread); if(nread == 0) { /* ctrl-c at the other end */ break; } for (int i = 0; i < nread; i++){ do_debug("%02hhx ", buffer[i]); } do_debug("\n"); net2tap++; // if (nread > 200) printf("recv:%d\n", nread); /* read packet */ // nread = read_n(net_fd, buffer, ntohs(plength)); // do_debug("NET2TAP %lu: Read %d bytes from the network\n", net2tap, nread); /* now buffer[] contains a full packet or frame, write it into the tun/tap interface */ nwrite = write(tap_fd, buffer, nread); do_debug("NET2TAP %lu: Written %d bytes to the tap interface\n", net2tap, nwrite); if (connected_flag == 0) { my_err("baseband successful\n"); connected_flag = 1; } #if 0 do_debug("NET2TAP %lu: ", net2tap); for (int i = 0; i < nwrite; i++){ if (buffer[i] != 0) fprintf(ue_fd, "%02hhx ", buffer[i]); do_debug("%02hhx ", buffer[i]); } fprintf(ue_fd, "\n"); do_debug("\n"); #endif } } return(0); }

林当时
  • 粉丝: 125
上传资源 快速赚钱