Network communication protocol TCP

The TCP layer is the application layer, TCP provides reliable data transfer service to the object-oriented application layer, TCP implements data transmission from a data transfer application to another application. It can provide a highly reliable communications (i.e. data is correct, no loss of data, no data is out of order, without duplication of data arriving communication), an application submits data to the TCP layer by sending access address and port number / terminating the Application Layer data communications.
Can only distinguish two devices connected by a network IP source / destination, the network connection can be divided into two by a socket application source / destination region only.
Three-way handshake
must first establish TCP is a connection-oriented, so-called connection-oriented, that is, when both the computer communication connection and data communication, and finally dismantle three connection process. In the TCP connection establishment time and divided into three steps:
the first step (A-> B): Host A to Host B sends a SYN i.e. contains synchronization (the Synchronize) flags TCP packet, SYN synchronization packet will specify use of the client TCP port number and the initial connection;
the second step (B-> a): host B after receiving the client SYN packet, it returns a SYN + ACK packet, the host B represents a request is accepted, while TCP sequence number is increased by one, ACK i.e. acknowledgment (Acknowledgement).
Step (A-> B): Host A also returns an acknowledgment message ACK to the server, the same TCP sequence number is incremented by one, a TCP connection is completed to this
TCP / IP protocol core
three-way handshake

UDP
UDP User Datagram Protocol i.e., an unreliable transport protocol for non-connection, without going through a 3-way handshake to establish a connection at the same time, a UDP client application or server-side applications as simultaneously.
Since the UDP protocol does not need to establish a clear connection, so the establishment of TCP and UDP applications than build applications much simpler. UDP is more efficient than the TCP protocol, can better address real-time issues, now includes online video conferencing system, including a large number of client / server model of network applications use UDP protocol.

TCP / IP core protocol
Protocol selection
Select protocol should take into account data reliability, the reliability of real-time applications and networks.
Data application requires high reliability requirements of the TCP protocol selected, the reliability is not so high for data applications selectable UDP transport.

TCP 3-way handshake protocol, the retransmission confirmation means can ensure the reliability of data transmission, but there will be greater using the TCP protocol delay and therefore not suitable for the demanding real-time applications; UDP, however, there are good real-time.
The network conditions are not good circumstances need to use the TCP protocol (as in the case of a wide area network, etc.), select UDP protocol can reduce the network load situation under good network conditions.

Socket is a network interface, the difference operation between different protocols, the solution to the socket itself
is a special IO interface, a file descriptor;
is a communication process between a common, locally, communication between hosts;
the Socket available network address structure
{protocol, local address, local port} indicates

Socket type:
1. stream socket SOCK_STREAM
Stream sockets provide a reliable, connection-oriented traffic flows. It uses the TCP protocol. TCP ensures the correctness and sequence of data transmission;
2. datagram sockets SOCK_DGRAM
datagram socket defines a connectionless service, data is transferred through packets independently, is disordered, and does not guarantee reliable, error-free, that uses datagram protocol UDP.
3. SOCK_RAM raw socket
raw sockets such as IP ICMP allows direct access to the low-level protocol or, mainly for the new network protocol testing the like.
The underlying protocol access, not convenient for some protocol development.

Address structure:

struct sockaddr_in
    {
       short int sin_family;  /* Internet地址族 */
       unsigned short int sin_port;  /* 端口号 */
       struct in_addr sin_addr;   /* IP地址 */
       unsigned char sin_zero[8];  /* 填0 */
     };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
   编程中一般并不直接针对sockaddr数据结构操作,而是使用与sockaddr等价的sockaddr_in数据结构

Now let's look at a process-based TCP / IP servers
1. Create a socket, a function socket ()
2. Binding information IP address and port to the socket, with the function the bind ()
3. Set allowed maximum number of connections with the function the listen ()
4. receiving a client connection served by the function Accept ()
5. the send and receive data, a function send () and the recv (), or a read () and Write ()
6. the closed network connection

End of the TCP / IP based customer
1. Create a socket, a function Socket ()
2. Set the other properties to be connected IP address and port
3. The connection server () function with the Connect
4. send and receive data, send a function () and the recv (), or a
read () and Write ()
5. The network connection off

1, socket ()
function returns: Create a socket () socket
header function: #include <sys/socket.h>
Prototype function: int socket(int domain, int type, int protocol);
function parameters:
the Domain: which indicates the type of address used
AF_INET: IPV4 network protocol network
AF_INET6: IPV6 network protocol
Type : SOCK_STREAM, TCP: stream-oriented data
SOCK_DGRAM, UDP: discontinuous untrusted connection packet
SOCK_RAW provide an original network protocol
protocol: specify a transport protocol number, usually set to 0 to
the return value of the function:
success: Back socket word descriptors
error: -1

2, bind ()
function returns: IP address binding
function prototype: int bind(int sockfd, struct sockaddr * hostaddr, int addrlen)
function header file:#include <sys/types.h>

#include <sys/socket.h>
  • 1
  • 1

Function parameters:
sockfd: Socket socket descriptor
Hostaddr: Host Address
Addrlen: address length of sockaddr

    Struct sockaddr_in
    {
        Unsigned short sin_family;       网络协议
        Uint6_t  sin_port;             端口号
        Struct in_addr sin_addr;          地址
        Unsigned char size_zero[8];        未使用
    };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3, listen ()
function returns: monitor network, wait for a connection
function prototype: int listen(int sockfd, int backlog)
function parameters:
sockfd: socket descriptor
Backlog: allowing the number of clients access
the return value of the function:
success: return 0,
the error: return -1
* Note: listen and no connection, just set the socket listen mode, the real connection is accept.

4, accept ()
function returns: accept the network connection, the client connections (which is three-way handshake local)
function prototype: int accept (int sockfd, struct sockaddr * addr, int * addrlen);
function parameters:
sockfd: socket descriptor
Addr: the connection is successful, the client's address filling the distal end
addrlen: struct sockaddr length of
return value:
success: returns the new socket descriptor (new_sockfd) ... previous descriptor different
error : -1

5, send ()
function returns: after transferring data socket, to send data to the other
function prototype: int send(int new_sockfd, const void *msg, int len, unsigned int flags)
parameter function:
New_sockfd: established by accept socket connector descriptors, connection to the IP address of the distant
Msg: data transmitted
Len: data length transmitted
the Flags: 0 typically set
return value:
success: the number of bytes actually sent out
error: -1.

6, recv ()
function returns: receive data via socket
function prototype: int recv(int new_sockfd, void *buf, int len, unsigned flags)
parameter function:
New_sockfd: Accept socket after the socket descriptor
Buf: storage address
Len: length of the data received in
the Flags: generally 0 to
function return value:
success: returns the number of bytes received in
error: -1.

7, connect ()
function returns: establishing a socket connection, a client connecting to the server is typically
the function prototype: int connect(int sockfd, struct sockaddr *serv_addr, int addrlen)
function parameters:
sockfd: socket socket descriptor
Serv_addr: indicates the address of the server to connect
addrlen: the length of a struct sockaddr
return value:
success: returns 0
error: -1

8, sendto ()
function returns: the data transfer socket, typically using UDP
function prototype: int sendto(int sockfd, const void *msg, int len, unsigned int flags, const struct sockaddr *todaar, int tolen)
function parameters:
sockfd: socket descriptor
Msg: sending the message memory
Len: length message
Toaddr: To send a message the destination address
Tolen : sizeof (struct sockaddr)
function return value:
success: returns the number of bytes actually transferred
error: -1

9, recvfrom ()
function returns: receiving data from the socket
function prototype: int recvfrom(int sockfd, void *buf, int len, unsigned int flags, struct sockaddr * fromaddr, int fromlen)
parameter function: sendto same as
the return value of the function:
success: Returns the number of bytes actually received
error: -1.

Common endian conversion functions:
the first function file: #include <arpa/inet.h>
transmitted from the host to the network:
uint32_t htonl (uint32_t hostint32); 32-bit data transfer from the host to the network.
Uint16_t htons (uint16_t hostint16); 16-bit data transfer from the host to the network.

From the network to the host:
uint32_t ntohl (uint32_t netint32); 32-bit data received from the network to the host
Uint16_t ntohs (uint16_t netint16); 16-bit data received from the network #include

include

include

include

include

include

include

include

define portnumber 3333

int main(int argc, charchar *argv[])
{
int sockfd,new_fd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int sin_size;
int nbytes;
char buffer[1024];

. Socket //. 1
IF ((sockfd = Socket (AF_INET, SOCK_STREAM, 0)) == -. 1) // AF_INET: the IPV4; SOCK_STREAM: the TCP
{
fprintf (stderr, "the Socket error:% S \ n-\ A", the strerror (errno));
Exit (. 1);
}
//2.bind
bzero (& The server_addr, the sizeof (struct the sockaddr_in)); // initialization, set 0
server_addr.sin_family = AF_INET; // the Internet
server_addr.sin_addr.s_addr = htonl (INADDR_ANY); // (on the long data into the machine data on the network is long), and any host communication // INADDR_ANY represents arbitrary data received IP address, i.e., bind to all the IP
//server_addr.sin_addr .s_addr = inet_addr ( "192.168.1.1") ; // for binding to a fixed IP, inet_addr ip for the conversion to digital format, plus shaping ip
server_addr.sin_port = the htons (portnumber); // (present short on the machine data into the short data on a network) port number
// server_addr.sin_addr.s_addr = inet_addr ( "192.168.1.199" ); //; htonl (INADDR_ANY);

/* 捆绑sockfd描述符到IP地址 */     
if(bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)     
{     
    fprintf(stderr,"Bind error:%s\n\a",strerror(errno));     
    exit(1);     
}     

//3.listen
if (listen(sockfd, 5)==-1)
{
printf(“listen error\n”);
}
while(1)
{
sin_size=sizeof(struct sockaddr_in);
printf(“1\n”);
//4.accept
if( new_fd = accept(sockfd, (struct sockaddr *)(&client_addr), &sin_size) <0)
{
printf(“accept error.\n”);
}
fprintf(stderr,”Server get connection from %s\n”,inet_ntoa(client_addr.sin_addr));
//5.recv/send
if((nbytes=read(new_fd,buffer,1024))==-1)
{
fprintf(stderr,”Read Error:%s\n”,strerror(errno));
exit(1);
}
buffer[nbytes]=’\0’;
printf(“Server received %s\n”,buffer);

    /* 这个通讯已经结束 */     
    close(new_fd);     
    /* 循环下一个 */     
}     

/* 结束通讯 */     
close(sockfd);     
exit(0);     

} `

include

include

include

include

include

include

include

include

define portnumber 3333

int main()
{
int sockfd;
struct sockaddr_in serv_addr;
int addlen=sizeof(struct sockaddr);
char buf[512]=”hello world”;

//1.socket
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0))==-1)
{
printf(“socket error”);
}

 bzero(&serv_addr,sizeof(serv_addr));    
 serv_addr.sin_family = AF_INET;    
 serv_addr.sin_port =  htons(portnumber);    
 serv_addr.sin_addr.s_addr=inet_addr("192.168.1.199");    
//2.connect    
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) <0)    
{    
    printf("connect error\n");    
}    





//3.send    

if( send(sockfd, buf, strlen(buf), 0 ) <0)
{
printf(“send error\n”);
}
//4.close
close(sockfd);
}

Guess you like

Origin blog.csdn.net/wujiafei_njgcxy/article/details/77148817