In the third quarter - Lesson 24 -TCP communications programming

Lesson 24 -TCP communications programming

 

 

24.1 TCP function of the programming model

Inside this framework we use is a lesson framework. That we need to build a server but also to build a client. Performing the following steps:

Server: Create a socket (socket), bind address (bind), listening port (listen), waits for a connection (accept), send / receive data (send / receive), the end of the connection (close).

Client: Create a socket (socket), connect to the server (connet), send / receive data (send / receive), the end of the connection (close).

There are more than a total of eight functions, introduced one by one the following:

1. Create a socket

(1) function name

socket()

(2) Function Prototype

int socket(int domain, int type, int protocol);

(3) function-

Create a socket

(4) contained in the header file

#include<sys/socket.h>

(5) Return value

Success: returns the file (socket) descriptor;

Failure: -1

(6) Parameter Description

domain: determining communication properties.

AF_INET (IPv4 Internet domain);

AF_INET6 (IPv6 Internet domain);

AF_UNIX(UNIX域);

AF_UNSPEC (not specified).

type: determining the type of socket.

SOCK_DGRAM (fixed length, connectionless unreliable message delivery);

The SOCK_RAW (datagram interfaces, POSIX.1 IP protocol is optional);

SOCK_SEQPACKET (fixed length, orderly, reliable connection-oriented message delivery);

SOCK_STREAM (ordered, reliable, bi-directional byte stream oriented connection).

protocol: usually 0, indicating the identified communication protocol in accordance with the parameters domain and type.

 

2. Bind address

(1) function name

bind()

(2) Function Prototype

int bind(int sockfd, const struct sockaddr *addr, socklen_t len);

(3) function-

Addresses are bound to drop a socket.

(4) contained in the header file

#include<sys/socket.h>

(5) Return value

Success: 0;

Failure: -1

(6) Parameter Description

sockfd: socket fd

addr: address binding

len: length of address binding

We will structure listed:

struct sockaddr

{

sa_family_t sa_family;

char sa_data [14];

}

This is a generic address type (IPv4 and IPv6), a member of the first family indicates an address of the type of protocol, a second value representing a particular member address. But we usually use ipv4 addresses are, to a certain evolution on the structure:

struct sockaddr_in

{

short int            sin_family;

unsigned short int    sin_port;

struct in_addr        sin_addr;

unsigned char        sin_zero[8];

}

struct in_addr

{

unsigned long s_addr;

}

In order to distinguish the difference between these two methods, we use the form:

Protocol suite

 

Protocol family (AF_INET)

 

Address (14 bytes)

Port number (2 bytes)

IP address (4 bytes)

Filling (8 bytes)

 

Note: ip address used in our lives is similar to 192.168.1.1 this, but ip address us our program is an integer, so take some conversion. We offer the following two functions:

l  in_addr_t inet_addr(const char *cp)

Function: The IP address string into integer IP address (Network Byte Order)

Examples: in_addr.saddr = inet_addr ( "192.168.1.1");

 

char * p inet_ntoa (struct in_addr)

Function: integer of Ip address into the IP address string.

 

3. Set the listening port

(1) function name

listen()

(2) Function Prototype

int listen(int sockfd, int backlog);

(3) function-

Declaring the connection request can be accepted.

(4) contained in the header file

#include<sys/socket.h>

(5) Return value

Success: 0;

Failure: -1

(6) Parameter Description

sockfd: socket fd

backlog: providing a prompt to represent the team's connection to the process required number of requests. The actual value thereof determined by the system.

 

4. Wait for connection

(1) function name

accept()

(2) Function Prototype

int accept(int sockfd, struct sockaddr *restrict addr, socklen_t *restrict len);

(3) function-

Once the server calls listen, you will be able to close the socket connection request. Accept the connection request is obtained using a function and establish a connection. The client is not connected to the server can occur blocked.

(4) contained in the header file

#include<sys/socket.h>

(5) Return value

Success: File (lexical) descriptor; a new file descriptor, the operation after it is used.

Failure: -1

(6) Parameter Description

sockfd: File (lexical) descriptor;

addr: The address of the client record here;

len: address length

 

5. Data transmission

(1) function name

send()

(2) Function Prototype

ssize_t send(int sockfd, const void *buf, size_t nbytes, int flags);

(3) function-

And write like it, but may change the mode designation flag to process the transmission data. When using the send socket it must be already connected.

(4) contained in the header file

#include<sys/socket.h>

(5) Return value

Success: Returns the number of bytes sent;

Failure: -1

(6) Parameter Description

sockfd: socket fd, fd is the use accept the establishment of the return connection;

buf: a stored position data transmitter

nbytes: the length of the transmission data

flags: flags, if not set to 0; include the following symbols:

MSG_DONTROUTE: Do the local network to route the data

MSG_DONTWAIT: Allow non-blocking operations (equivalent to the O_NONBLOCK)

MSG_EOR: If the protocol support, this is the end of the record

MSG_OOB: If the protocol supports, the transmission band data

6. Receive data

(1) function name

recv()

(2) Function Prototype

ssize_t recv(int sockfd, void *buf, size_t nbytes, int flags);

(3) function-

It read like, but allows you to specify options to control how to receive data.

(4) contained in the header file

#include<sys/socket.h>

(5) Return value

Successful: the length in bytes of the message, or other message has no free ends sequentially return 0;

Failure: -1

(6) Parameter Description

sockfd: socket fd, fd is the use accept the establishment of the return connection;

buf: receiving position data stored

nbytes: the length of the received data

flags: Flag;

 

7. Close connection

Close function close (sockfd), and the file is the same.

 

8. Connection Server

(1) function name

connect()

(2) Function Prototype

int connect(int sockfd, const struct sockaddr *addr, socklen_t len);

(3) function-

If the process is a network service (SOCK_STREAM or SOCK_SEQPACKET) connection-oriented, before starting to exchange data, you need to establish a connection between the process socket (client) requesting service and process serving socket (server) . This is the role connect function.

(4) contained in the header file

#include<sys/socket.h>

(5) Return value

Success: 0;

Failure: -1

(6) Parameter Description,

sockfd: socket fd created on the client;

addr: address of the server;

len: address length.

 

24.2 network byte order

Big-endian byte order (big-endian): not according to the direction of growth of the memory, the higher order data is stored in low memory.

Little-endian byte order (little-endian): according to the direction of growth of the memory, the upper data storage in upper memory.

Communication between two hosts A and B, if the two hosts is a large end communications a little endian communication, so that it will send the byte order is reversed. This requires the use of network byte order, which is actually a size of a predetermined host terminal during communication. Corresponding to network byte order is big endian mode, the sender if we have a little endian first end larger than its conversion mode.

But for the receiving end, and we find it necessary to store the receiver in the end to see what mode. If the big endian mode, according to the big endian mode memory; if little-endian mode, the storage mode to press the small end.

In linux system, four conversion functions in network byte order, as follows:

1. uint32_t htonl(uint32_t hostlong);

The 32-bit data from host to network byte order word

in_addr.saddr = htonl(INADDR_AN

2. uint16_t htons(uint16_t hostshort);

The 16-bit data from host to network byte order byte order

3. uint32_t ntohl(uint32_t netlong);

The converted 32-bit data from the host to network byte order byte sequence

  1. 4.  uint16_t ntohs(uint16_t netshort);

The 16-bit data from the host to network byte order byte sequence

 

 

Examples of the preparation of 24.3

TCP Communications Programming

tcp_server.c

#include<sys/socket.h>

#include<stdio.h>

#include <string.h> // string header

Headers #include <netinet / in.h> // address

#define portnum 3333

int main ()

{

 

         int sockfd;

         int new_fd;

         char buffer [128]; // definition storing data bytes

         int nbyte; // length of the received string

         int sin_size;

         struct sockaddr_in server_addr;

         struct sockaddr_in client_addr;

         1 // Create a socket

         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)

         {

                  printf("creat socket error!\n");

                  exit(1);

         }

         //2.1 set the address to bind

         bzero(&server_addr, sizeof(struct sockaddr_in));//清零

         server_addr.sin_family = AF_INET; // network protocol

         server_addr.sin_port = htons (portnum); // port, more than two bytes will convert

         server_addr.sin_addr.s_addr = htonl (INADDR_ANY); // indicates any address, will convert more than two bytes

         //2.2 bind address

         bind (sockfd, (struct sockaddr *) (& server_addr), sizeof (struct sockaddr)); // pointer indicates cast

         // 3. Listen Port

         listen(sockfd, 5);

         while(1)

         {

         // 4. Waiting for connection

         sin_size = sizeof(struct sockaddr);

         new_fd = accept(sockfd, (struct sockaddr *)(&client_addr), &sin_size);

         printf ( "server get connection from% s \ n", inet_ntoa (client_addr.sin_addr)); // get ip address of the client, and converts the address to the address of the string integer

         5 // received data

    nbyte = recv(new_fd,buffer,128,0);

         buffer [nbyte] = '\ 0'; // string terminator

         printf("server received: %s \n",buffer);

         // 6. End connections

         close(new_fd);

         }

         close(sockfd);

         return 0;

}

 

tcp_client.c

 

#include<sys/socket.h>

#include<stdio.h>

#include <string.h> // string header

Headers #include <netinet / in.h> // address

#define portnum 333 // no semicolon

int main ()

{

         int sockfd;

         char buffer [128]; // we save the data input

         struct sockaddr_in server_addr;

         1 // Create a socket

         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)

         {

                  printf("creat socket error!\n");

                  exit(1);

         }

         //2.1 set the server to connect to the address

         bzero(&server_addr, sizeof(struct sockaddr_in));//清零

         server_addr.sin_family = AF_INET; // network protocol

         server_addr.sin_port = htons (portnum); // port, more than two bytes will convert

         server_addr.sin_addr.s_addr = inet_addr("192.168.153.129");

         // services that address theory should be passed in through the main function, but to write it here for the convenience of the dead.

         //2.2 connect to the server

         if(connect(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1)

         {

                  printf("connect error!\n");

                  exit(1);

         }

         // 3. Transmits data to the server

         printf("please input char:\n");

         fgets(buffer,128,stdin);

         send(sockfd, buffer, strlen(buffer),0);

         // 4 socket key

         close(sockfd);

         return 0;

}

run:

         After the compiled file gcc, two identical open end, in which one end of the run ./tcp_server, ./tcp_client run at another terminal. Tcp_client character input terminal, can be displayed tcp_server.

Guess you like

Origin www.cnblogs.com/free-1122/p/11357245.html