动手学习TCP系列之环境搭建(1)
动手学习TCP系列之环境搭建(1)
环境搭建和配置
在开始进行实验之前,首先看看实验环境的搭建:
Wireshark:用来抓取网络上的包,可以清楚的看到TCP/IP协议层,以及每层的详细信息,通过此处下载
一台虚拟机:如果客户端和服务端都在本机,那么数据通信是不经过网卡的,所以Wireshark就抓不到任何数据包。方便的办法就是本机安装一个虚拟机,通过本机和虚拟机通信进行实验。我使用的是VirtualBox+winXP.
Pcap.Net:是一个WinPcap的.NET wrapper,基于这个库,我们就可以很方便的通过C#代码来实现下面功能(通过此处下载):
获取网络设备
接收、解析数据包
创建、发送数据包
在建立好实验环境之后,还需要进行一些简单的配置,保证宿主机和虚拟机之间的网络是畅通的。
将虚拟机网络设置为"Host-only Adapter"模式。
虚拟机网络设置好之后,就可以配置本机和虚拟机IP地址了,然后保证宿主机可以ping通虚拟机。
环境验证
通过上面的步骤,简单的实验环境就建立完成了,下面就要来实现客户端和服务端了,试试实验环境是否能够正常工作。
服务端
首先,将虚拟机(192.168.56.102)作为服务端,运行下面一段代码创建一个简单的socket server,服务端绑定192.168.56.102:8081:
import sys from socket import * HOST = "192.168.56.102" PORT = 8081 BUFSIZ = 1024 ADDR = (HOST, PORT) server = socket(AF_INET, SOCK_STREAM) print "Socket created" try: server.bind(ADDR) except error, msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() server.listen(10) print 'Socket now listening' while True: conn, addr = server.accept() try: data = conn.recv(100) if data: print data except Exception, e: print e conn.close()
客户端
客户端的实现在本机(192.168.56.101),使用一段基于Pcap.Net的代码向服务器发送一个[SYN]包(TCP连接建立需要进行三次握手,[SYN]包就是第一个握手包),来请求建立TCP连接。
在客户端代码中,通过Pcap.Net实现了两个工具函数,一个用来获取本机网卡设备列表,一个用在构造不同类型的TPC包。
获取本机网卡设备列表代码:
public static PacketDevice GetNICDevice() { // Retrieve the device list from the local machine IListallDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return null; } // Print the device list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) Console.WriteLine(" (" + device.Description + ")"); else Console.WriteLine(" (No description available)"); } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); return allDevices[deviceIndex - 1]; }
评论暂时关闭