The previous time through the Wireshark grab packet, positioning a client and server data transfer between the problem. Recently took the time to look at "TCP/IP Detailed Volume 1" In the section on TCP, the book used a lot of examples to show some of the basic concepts of TCP/IP protocol.
So, be prepared to do it yourself, and learn some of the basic concepts in TCP with some simple experiments.
Environment Construction and configuration
Before starting the experiment, let's look at the setup of the experimental environment:
- Wireshark: Used to crawl packets on the network, you can clearly see the TCP/IP protocol layer, as well as the details of each layer, download here
- A virtual machine: if both the client and the server are in the local, then data communication is not through the network card, so wireshark can not catch any packets. A convenient way to do this is to install a virtual machine and experiment with the native and virtual machine communication. I'm using the VIRTUALBOX+WINXP.
- Pcap.net: is a winpcap. Net wrapper, based on this library, we can easily use C # code to implement the following features (download here):
- Get Network devices
- Receiving and parsing packets
- Create, send Packets
After establishing the experimental environment, some simple configuration is needed to ensure that the network between the host and the virtual machine is unblocked.
Set the virtual machine network to "Host-only Adapter" mode.
After the virtual machine network is set up, you can configure the native and virtual machine IP addresses, and then ensure that the host can ping the virtual machine.
Environmental validation
Through the above steps, the simple experimental environment is established, the following is to implement the client and server, try to test the environment can work properly.
Service side
First, the virtual machine (192.168.56.102) as the server, run the following code to create a simple socket server, the server-side binding 192.168.56.102:8081:
ImportSYS fromSocketImport*HOST="192.168.56.102"PORT= 8081Bufsiz= 1024ADDR=(HOST, PORT) server=socket (af_inet, sock_stream)Print "Socket created"Try: Server.bind (ADDR)excepterror, msg:Print 'Bind failed. Error Code:'+ str (msg[0]) +'Message'+ msg[1] Sys.exit () Server.listen (10)Print 'Socket now listening' whileTrue:conn, addr=server.accept ()Try: Data= CONN.RECV (100) ifData:PrintDataexceptException, E:Printe conn.close ()
Client
The implementation of the client is in native (192.168.56.101), using a section of Pcap.net-based code to send a [SYN] packet to the server (TCP connection establishment requires three handshake, [SYN] packet is the first handshake packet) to request the establishment of a TCP connection.
In the client code, the Pcap.net implements two tool functions, one for obtaining a list of native NIC devices, and one for constructing different types of TPC packages.
Get the native NIC device List code:
Public StaticPacketdevice Getnicdevice () {//Retrieve The device list from the local machineIlist<livepacketdevice> alldevices =Livepacketdevice.alllocalmachine; if(Alldevices.count = =0) {Console.WriteLine ("No Interfaces found! Make sure WinPcap is installed."); return NULL; } //Print the device list for(inti =0; I! = Alldevices.count; ++i) {Livepacketdevice device=Alldevices[i]; Console.Write ((i+1) +". "+device. Name); if(Device. Description! =NULL) Console.WriteLine (" ("+ device. Description +")"); ElseConsole.WriteLine ("(No description available)"); } intDeviceindex =0; Do{Console.WriteLine ("Enter The interface number (1-"+ Alldevices.count +"):"); stringDeviceindexstring =Console.ReadLine (); if(!int. TryParse (Deviceindexstring, outDeviceindex) | |Deviceindex<1|| Deviceindex >alldevices.count) {Deviceindex=0; } } while(Deviceindex = =0); returnAlldevices[deviceindex-1];}
Another important piece of code is the code that constructs the TCP package, which, according to the OSI seven layer model, creates a section of the link layer, the network layer, and the transport layer, respectively, and then generates a packet:
Public StaticPacket Buildtcppacket (Endpointinfo endpointinfo, Tcpcontrolbits tcpcontrolbits, list<tcpoption> tcpOptionList =NULL) {Ethernetlayer Ethernetlayer=NewEthernetlayer {Source=NewMacAddress (Endpointinfo.sourcemac), Destination=NewMacAddress (Endpointinfo.destinationmac), EtherType= Ethernettype.none,//Would be filled automatically. }; Ipv4layer Ipv4layer=NewIpv4layer {Source=Newipv4address (ENDPOINTINFO.SOURCEIP), Currentdestination=Newipv4address (Endpointinfo.destinationip), fragmentation=Ipv4fragmentation.none, Headerchecksum=NULL,//Would be filled automatically.Identification =123, Options=Ipv4options.none, Protocol=NULL,//Would be filled automatically.TTL =Ten, Typeofservice=0, }; Tcplayer Tcplayer=NewTcplayer {sourceport=Endpointinfo.sourceport, Destinationport=Endpointinfo.destinationport, Checksum=NULL,//Would be filled automatically.SequenceNumber =SeqNum, Acknowledgmentnumber=Acknum, Controlbits=tcpcontrolbits, Window=windowsize, Urgentpointer=0, Options= (Tcpoptionlist = =NULL) ? Tcpoptions.none:Newtcpoptions (tcpoptionlist),}; Packetbuilder Builder=NewPacketbuilder (Ethernetlayer, Ipv4layer, Tcplayer); returnBuilder. Build (DateTime.Now);}
The main program first configures the client and server port, Ip/mac address information, and then constructs a TCP connection to create the request packet ([SYN] packet) through the preceding two tool functions, and sends it to the service side via the "VirtualBox host-only Network" network card.
Static voidMain (string[] args) { //Take the selected adapterPacketdevice Selecteddevice =Utils.getnicdevice (); //Open the output device using(Packetcommunicator Communicator = Selecteddevice.open (System.Int32.MaxValue,//name of the devicePacketdeviceopenattributes.promiscuous,//Promiscuous Mode 1))//Read Timeout{endpointinfo Endpointinfo=NewEndpointinfo (); Endpointinfo.sourcemac="08:00:27:00:c0:d5"; Endpointinfo.destinationmac="08:00:27:70:a6:ae"; Endpointinfo.sourceip="192.168.56.101"; Endpointinfo.destinationip="192.168.56.102"; Endpointinfo.sourceport=3330; Endpointinfo.destinationport=8081; using(Berkeleypacketfilter filter = Communicator.) Createfilter ("TCP Port"+endpointinfo.destinationport)) {//Set the filterCommunicator. SetFilter (filter); } communicator. Sendpacket (Utils.buildtcppacket (Endpointinfo, Tcpcontrolbits.synchronize,NULL)); Packethandler (Communicator, Endpointinfo); } Console.WriteLine ("Press Enter to quit!"); Console.ReadLine ();}Private Static voidPackethandler (Packetcommunicator Communicator, Endpointinfo endpointinfo) {Packet Packet=NULL; Do{packetcommunicatorreceiveresult result= Communicator. Receivepacket ( outpacket); Switch(Result) { Casepacketcommunicatorreceiveresult.timeout://Timeout Elapsed Continue; CasePacketCommunicatorReceiveResult.Ok:Utils.PacketInfoPrinter (packet); Break; default: Throw NewInvalidOperationException ("The result"+ result +"should never being reached here"); } } while(true);}Run code
The code is finished, the following look at the running effect, in order to visually see the transmission of the packet, it is possible to open the Wireshark.
To avoid catching unrelated packets, you can set the filter in the Wireshark and start crawling.
Run the code below and select the correct NIC. With the console and Wireshark output, we have successfully produced a [SYN] packet and sent it to the server.
Depending on the TCP connection setup process, it is known that the client sends a [SYN] packet and expects to get a [SYN, ACK] packet from the server.
Here, it shows that the environment in front of you, as well as the client and server code are working properly.
Who's [RST] Package
As seen from the above results, the client sends a [RST] packet to reset the TCP connection after receiving the [SYN, ACK] packet.
After careful review of the code discovery, the client's code did not send the [RST] package. So where does this [RST] package come from?
The operating system has the concept of protocol stack, so the data from the application layer will be layered through the operating system protocol stack processing, and then sent through the network card.
When the client NIC receives the [SYN, ACK] packet, the package is captured by our Pcap.net program and also sent to the client operating system. Because the [SYN] packet constructed through pcap.net is not on the operating system protocol stack, the operating system considers the [SYN, ACK] packet to be an invalid TCP packet and resets the TCP connection through the [RST] packet.
Here, the extra [RST] package can be explained.
Avoid [RST] Packages
In order to avoid the effect of the operating system protocol stack on the Pcap.net program, the setting of IP Security policy (via run-> "secpol.msc" open setting) You can prevent the operating system from sending packets to the virtual machine (192.168.56.102) from the native (192.168.56.101).
Once setup is complete, run the program again, which is normal for the program.
Because the client does not send the [ACK] packet to confirm the [SYN, ACK] packet from the server, the server is re-routed based on how TCP works.
Summarize
In this paper, we introduce the construction of TCP experiment environment, create a client through Pcap.net, can construct different kinds of TCP packets and send them to the server through a certain network card.
The following continues to look at some of the basic concepts of TCP, TCP connectivity, state transitions, and so on based on this environment.
Hands-On learning TCP: Environment building