Sending TCP Packets

Source: Internet
Author: User
Tags ack int size socket

First, the purpose of the experiment:

The function of this design is to populate a TCP packet and send it to the destination host.

Second, the experimental requirements:

1) Run as command line: sendtcp source_ip source_port dest_ip dest_port

Where Sendtcp is the program name, SOURCE_IP is the source IP address, Source_port is the source port, DEST_IP is the destination IP address, and Dest_port is the destination port.

2) Other TCP header parameters, please set your own.

3) The data fields are "This is my homework of network, I am happy!".

4) After successful sending, output "send OK" on the screen.

Third, design-related knowledge:

TCP, English full name transmission Control Protocol, is a connection-oriented, reliable, bitstream-based Transport layer communication protocol. TCP protocol and IP protocol are the most widely used TCP/IP protocol families in the Internet.

1. Overview of TCP Functions

When the application layer sends a 8-byte data stream for inter-network transmission to the TCP layer, TCP divides the data stream into segments of appropriate length, and the maximum transmission segment size (MSS) is usually limited by the maximum Transmission Unit (MTU) of the data link layer of the network to which the computer is connected. TCP then passes the packet to the IP layer, which transmits the packet over the network to the TCP layer of the receiving side entity. In order to guarantee the reliable transmission of the message , TCP gives each packet a serial number, and the serial number also guarantees the sequential reception of the packets sent to the receiving end entity. The receiving entity then sends a corresponding acknowledgment (ACK) to the successfully received byte, and if the sending entity does not receive a confirmation within a reasonable round trip delay (RTT), then the corresponding data (assuming it is lost) will be re-transmitted.

(1) in the correctness and legality of data, TCP uses a checksum function to verify the data for errors, to calculate the checksum at the time of sending and receiving, and to encrypt the data using MD5 authentication.

(2) in the guarantee of reliability, the use of time-out retransmission and the mechanism of the piggyback confirmation.

(3) In the flow control, the use of Sliding window protocol, the Agreement, for the window within the unconfirmed group needs to be re-transmitted.

in congestion control, a widely acclaimed TCP congestion control algorithm (also called AIMD algorithm) is adopted. The algorithm mainly includes three main parts: 1) Castian, multiplicative subtraction, 2) slow start, 3) respond to timeout events.

2. TCP connection Establishment

TCP is the Transport layer protocol in the Internet, using three-time handshake protocols to establish a connection. When the active party sends a SYN connection request, it waits for the other person to answer the Syn+ack and eventually performs an ACK acknowledgment on the other's syn. This method of establishing a connection prevents the wrong connection from being generated, and the traffic control protocol used by TCP is a variable-sized sliding window protocol.

The process for the TCP three-time handshake is as follows:

(1) The client sends a SYN (SEQ=X) message to the server side and enters the Syn_send state.

(2) The server receives the SYN message, responds to a SYN (seq=y) ACK (ack=x+1) message, and enters the SYN_RECV state.

(3) The client receives the server-side SYN message, responds to an ACK (ack=y+1) message, and enters the established state.

Three times the handshake is complete, the TCP client and server side successfully establish the connection and can begin transmitting data.

3. Termination of TCP connection

Establishing a connection requires three handshakes, while terminating a connection takes four handshakes, which is caused by a semi-shutdown of TCP (Half-close). The process is shown in the following figure.

(1) An application process first calls close, which is said to perform "active close" on that side. TCP on that side then sends a FIN section indicating that the data has been sent.

(2) The peer of the fin is received to perform a "passive shutdown" (passive close), which is confirmed by TCP.

Note: The receive of fin is also passed as a file terminator (End-of-file) to the receive end application process, placed after any other data that has been queued for the application process, because the receipt of fin means that the receiving application process has no additional data to receive on the corresponding connection.

(3) After a period of time, the application process that receives this file terminator will call close to close its socket. This causes its TCP to also send a fin.

(4) The original sender TCP receiving this final fin (i.e. the end of the active shutdown) confirms the fin.

Since each direction requires a fin and an ACK, it usually requires 4 sub-sections. [2]


(1) "Usually" means that, in some cases, the fin of step 1 is sent along with the data, and the sections sent by step 2 and step 3 are from the end of the passive shutdown, and may be merged into a sub-section.

(2) Between step 2 and step 3, from the execution of the passive closed end to the execution of the active closed one end of the flow of data is possible, this is called "semi-closed" (half-close).

(3) When a UNIX process terminates either voluntarily (calling exit or returning from the main function) or involuntarily (receiving a signal terminating the process), all open descriptors are closed, which also causes a fin to be emitted on any TCP connection that is still open.

Either the client or the server can perform an active shutdown on either side. Typically, the client performs an active shutdown, but some protocols, such as http/1.0, are actively shut down by the server.

4. How TCP provides reliability

TCP provides a connection-oriented, reliable byte-stream service. Connection-oriented means that two applications that use TCP (typically a customer and a server) must establish a TCP connection before exchanging packets with each other. This process is very similar to the phone call, first dial ringing, waiting for the other side to say "Hello", and then to explain who. In a TCP connection, only two parties communicate with each other. Broadcasts and multicasting cannot be used with TCP.

TCP provides reliability in the following ways:

(1) The application data is divided into the data blocks that TCP considers most suitable for sending. This is completely different from UDP, and the length of the data the application produces will remain the same. The unit of information that is passed to the IP by TCP is called a message segment or segment (segment).

(2) When TCP sends a segment, it initiates a timer, waiting for the destination to acknowledge receipt of the message segment. If a confirmation cannot be received in time, the message segment will be re-sent. When TCP receives data from the other end of the TCP connection, it sends an acknowledgment. TCP has a delayed acknowledgment feature, which is not turned on, and is immediately acknowledged. function is turned on, it is triggered by the timer to confirm the point in time.

(3) TCP will keep its header and data checked and. This is an end-to-end test and is designed to detect any changes in the data during transmission. If the test and errors are received, TCP discards the segment and does not acknowledge receipt of this segment (expecting the originator to timeout and re-send).

(4) Since the TCP packet is transmitted as an IP datagram, and the arrival of the IP datagram may be out of order, the arrival of the TCP message segment may also be out of sequence. If necessary, TCP will reorder the received data and hand the received data to the application tier in the correct order.

(5) Since IP datagrams are duplicated, the receiving side of TCP must discard duplicate data.

(6) TCP can also provide flow control. Each side of a TCP connection has a fixed-size buffer space. The receiving side of TCP only allows the other end to send the data that the receiving buffer can accept. This prevents faster hosts from causing buffer overruns for slower hosts.

Two applications Exchange byte streams consisting of 8bit bytes over a TCP connection. TCP does not insert a record identifier in the byte stream. We'll call this the byte stream service (Bytestreamservice). If one party's application passes 10 bytes, then 20 bytes, and then 50 bytes, the other side of the connection will not know how many bytes the sender sent each time. As long as your receive cache is not stuffed, the TCP receiver will receive as much as you want. One end places the byte stream on the TCP connection, and the same byte stream appears at the other end of the TCP connection.

In addition, TCP does not explain the content of the byte stream. TCP does not know whether the transmitted data byte stream is binary or Ascⅱ characters, EBCDIC characters, or other type of data. The interpretation of the byte stream is explained by the application layer of both sides of the TCP connection.

This processing of byte streams is similar to the way the UNIX operating system handles files. The Unix kernel does not interpret what an application reads or writes, but instead gives it to the application for processing. For the Unix kernel, it cannot differentiate between a binary file and a text file.

5. TCP Header

The first format of TCP is shown in the figure below:

---Source port is 16 bits.

---Destination port is the destination, 16-bit.

---Sequence number is the first byte of the sending packet, 32 bits.

---Acknowledgment number is the confirmation sequence, 32 bits.

---Data offset is a 4-bit, the value of the field is the TCP header (including the option) length divided by 4.

---flag bit: 6-bit, Urg means urgent pointer field is meaningful:

ACK indicates acknowledgment number field is meaningful

PSH represents the push feature, and RST indicates a reset TCP connection

SYN indicates a SYN message (used when establishing a TCP connection)

Fin indicates no data to send (used when TCP connection is closed)

Window represents the free space of the receive buffer, 16 bits, used to tell the TCP connection to the maximum length of data that the peer can receive.

---Checksum is the checksum, 16 bits.

---Urgent pointers is an emergency pointer, 16 bits, only the URG flag bit is set when the field is meaningful, which represents the offset of the emergency data relative to the serial number (the value of the Sequence numbers field).

Four, experimental design analysis:

The goal of this course is to send a TCP packet that can be used to do the work using the original socket. The entire program consists of two parts that initialize the original socket and send the TCP packet.

1. Create an original socket and set IP header options
SOCKET sock;
Sock=wsasoccket (af_inet,sock_raw,ipproto_ip,null,0,wsa_flag_overlapped);

Here, we set the SOCK_RAW flag, which indicates that we are declaring an original socket type. To use the Send receive time-out setting, the flag location must be wsa_flag_overlapped. In this course design, the TCP packet is sent with its own IP address hidden, so we have to populate the IP header ourselves and set the IP header operation options. The flag is set to Ture, and the IP_HDRINCL option is set to indicate that you are constructing the IP header. Note that if you set the IP_HDRINCL option, you must have administrator permissions, or you must modify the registry:
Modifier key: Disablerawsecurity (type DWORD), change the value to 1. If not, add it.
BOOL flag=true;
setsockopt (sock, Ipproto_ip, IP_HDRINCL, (char *) &flag, sizeof (Flag));

int timeout=1000;

setsockopt (sock, Sol_socket,so_sndtimeo, (char*) &timeout, sizeof (timeout));

Here we use the basic socket sol_socket, set So_sndtimeo to use the Send timeout setting, and the time-out setting to 1000ms.

2. Construct IP headers and TCP headers
Here, the IP header and TCP header and the construction of the TCP pseudo-part are referenced below for their data structure.

3. Sub-functions for calculating checksums

In the process of populating the packet, it is necessary to call the function checksum that computes the checksum two times, respectively, to verify the IP header and TCP header (plus the pseudo-header), the implementation code is as follows:

USHORT Checksum (USHORT *buffer, int size)
unsigned long cksum=0;
while (size >1)
Size-=sizeof (USHORT);
if (size)
Cksum + = * (uchar*) buffer;
Cksum = (cksum >> +) + (Cksum & 0xFFFF);
Cksum + = (cksum >>16);
Return (USHORT) (~cksum);

Five, the Process flow chart:

Six, the specific program code:

#include <stdio.h>

#include <winsock2.h>

#include <ws2tcpip.h>

#include <time.h>

#include <windows.h>

#include <string.h>

#include <stdlib.h>

#include <iostream.h>

#pragma comment (lib, "Ws2_32.lib")

#define IPVER 4//IP Agreement booking

#define Max_buff_len 65500//Send buffer Max

typedef struct IP_HDR//define IP header


UCHAR H_verlen; 4 Head Ministerial, 4-bit IP version number

UCHAR tos; 8-bit Service type TOS

USHORT Total_len; 16 bits total length (bytes)

USHORT ident; 16-bit identification

USHORT Frag_and_flags; 3-bit flag bit

UCHAR TTL; 8-bit time-to-live TTL

UCHAR Proto; 8-bit protocol (TCP, UDP, or other)

USHORT checksum; 16-bit IP header checksum

ULONG SourceIP; 32-bit Source IP address

ULONG Destip; 32-bit Destination IP address


typedef struct TSD_HDR//define TCP pseudo header


ULONG saddr; Source Address

ULONG daddr; Destination Address

UCHAR Mbz; Useless

UCHAR PTCL; Protocol type

USHORT tcpl; TCP length


typedef struct TCP_HDR//define TCP header


USHORT Th_sport; 16-bit Source port

USHORT Th_dport; 16-bit Destination port

ULONG Th_seq; 32-bit serial number

ULONG Th_ack; 32 Digit Confirmation Number

UCHAR Th_lenres; 4-bit header length/6-bit reserved word

UCHAR Th_flag; 6-bit flag bit

USHORT Th_win; 16-bit window size

USHORT th_sum; 16-bit Checksum

USHORT th_urp; 16-bit emergency data offset


CheckSum: Sub-function for calculating checksums

USHORT Checksum (USHORT *buffer, int size)


unsigned long cksum=0;

while (size >1)



Size-=sizeof (USHORT);


if (size)


Cksum + = * (uchar*) buffer;


Cksum = (cksum >> +) + (Cksum & 0xFFFF);

Cksum + = (cksum >>16);

Return (USHORT) (~cksum);


int main (int argc, char* argv[])


Wsadata Wsadata;

SOCKET sock;

Ip_header Ipheader;

Tcp_header Tcpheader;

Psd_header Psdheader;

Char Sendto_buff[max_buff_len]; Send buffer

unsigned short check_buff[max_buff_len]; Tests and buffers

const char tcp_send_data[]={"This is my homework of networt,i am happy!"};

BOOL Flag;

int rect,ntimeover;

if (argc!= 5)


printf ("Useage:sendtcp soruce_ip source_port dest_ip dest_port \ n");

return false;


if (WSAStartup (Makeword (2,2), &wsadata)!=0)


printf ("WSAStartup error!\n");

return false;


if ((Sock=wsasocket (af_inet,sock_raw,ipproto_raw,null,0,wsa_flag_overlapped)) ==invalid_socket)


printf ("Socket Setup error!\n");

return false;



if (setsockopt (Sock,ipproto_ip,ip_hdrincl, (char*) &flag,sizeof (flag)) ==so Cket_error)


printf ("setsockopt ip_hdrincl error!\n");

return false;



if (setsockopt (sock, Sol_socket, So_sndtimeo, (char*) &ntimeover, sizeof (ntimeover)) ==socket_error)


printf ("setsockopt so_sndtimeo error!\n");

return false;


Populate IP Header

ipheader.h_verlen= (ipver<<4 | sizeof (Ipheader)/sizeof (unsigned long));

ipheader.tos= (UCHAR) 0;

Ipheader.total_len=htons ((unsignedshort) sizeof (Ipheader) +sizeof (tcpheader) +sizeof (tcp_send_data));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.