Network-based programming of Linux application design

Source: Internet
Author: User
Tags ack hostname to ip htons

1, TCP/IP Protocol Overview 1.1, OSI Reference Model and TCP/IP Reference Model the OSI protocol reference model is developed based on the recommendations of the International Organization for Standardization (ISO), from top to developmet into 7 tiers: Application layer, presentation layer, session layer, Transport layer, network layer, data link layer, physical layer. The TCP/IP protocol model, which distinguishes this from the beginning, follows a simple and clear design approach, simplifying the OSI 7-layer Reference Model to 4-tier, which is advantageous for implementation and use. The corresponding relationship between the TCP/IP protocol Reference Model and the OSI protocol Reference model is as follows: Network interface layer:It is responsible for converting the binary stream into a data frame and sending and receiving the data frame. It is important to note that the data frames are independent of the network Galaxy Transmission unit. Network layer:Responsible for encapsulating the data frame as an IP datagram and running the necessary routing algorithms. Transport Layer:Responsible for the communication between end-to-end connection and resume, the choice of transmission protocol depends on the data transmission method. Application layer:The network access that is responsible for applying the sequence, where the various processes are identified by the port. 1.2, TCP/IP protocol family TCP/IP is a large protocol family, it includes a number of protocols at various levels, enumerating the layers can only blame some important protocols, and give the protocol at different levels in the location: ARP:Used to obtain a hardware host address in the same physical network MPLS:Multi-Protocol label protocol. IP:Responsible for addressing and routing packets between the host and the network. ICMP:The protocol used to send a report about the transmission error of the packet; IGMP:protocol used by IP hosts to report host group members to local multicast routers; TCP:Provides a reliable communication connection for applications that are suitable for transmitting large amounts of data at one time and for applications that require response. UDP:Provides no-connection communication, and does not guarantee the delivery packet reliably, suitable for the transmission of a small amount of data at a time, the reliability of the application layer to be responsible. 1.3, TCP and UDP1, TCP (1) overview As with any other protocol, TCP wants to provide services to adjacent high-level, because the TCP is the application layer, so TCP data transmission from one application to another application. The application programmatically calls TCP and uses the TCP service to provide the data that needs to be sent to differentiate between the destination address and port number of the receiving data application. Typically an application opens a socket to use the TCP service, and TCP manages data transfer to other sockets. It can be said that the source/purpose of IP can uniquely differentiate between two devices in the network. (2) The three-Time Handshake Protocol TCP dialog is initialized by a three-time handshake. The purpose of the three-time handshake is to synchronize the sending and receiving of data segments, telling other hosts how much data they can pick up at a time, and establishing virtual links. the simple process of three-time handshake:1. Initialize the host to make a session request through a data segment with a synchronous flag set; 2. The receiving host responds by sending back data segments with the following items: The synchronization flag is set, the sequence number of the starting byte of the data segment that is being sent, and the reply with the byte order number of the next data segment that will be received. 3, request the host to return a data segment, and with confirmation sequence number and confirmation number. The process is as follows: The basic protocol used by TCP entities is the sliding window protocol. When the sender transmits a datagram, it starts the timer. When the datagram arrives at the destination, the receiver's TCP entity sends back a datagram that contains a confirmation ordinal, which means that it expects to receive the order number of the next datagram. If the sender's timer times out before the confirmation message arrives, the sender will resend the datagram. (3) TCP Data header TCP data header meaning is as follows: Source port, Destination port: 16 bits long. Identifies the remote and local port numbers. Serial number: 32 bits long. Identifies the order in which datagrams are sent. Confirmation Number: 32 bits long. The serial number of the next datagram that you want to receive. TCP head Length: 4 bits long. Indicates how many 32-bit words are contained in a TCP header. 6 bits unused. Ack:ack Position 1 indicates that the confirmation number is legal. If the ACK is 0, the datagram does not contain confirmation information and the confirmation field is omitted. PSH: Represents the data with the push flag, so the receiver requests the datagram to be sent to the application without waiting for the buffer to be filled before it is sent. RST: Used to reset error links that occur due to host crashes or other causes. It can also be used to reject illegal datagrams or deny connection requests. SYN: Used to establish a connection fin: Used to release the connection. Window Size: 16 bits long. The window size segment indicates how many bytes can be sent after the byte has been confirmed. Checksum: 16 bits long. is set to ensure high reliability. It examines the head, data pseudo-TCP header and the sum. Available options: 0 or more 32-bit words. Includes options such as maximum TCP load, window scale, and selection of re-send datagrams. 2. The UDPUDP protocol does not need to establish a clear connection, so it is much simpler to build a UDP application than to establish a TCP application. UDP packet Header as shown: Source address, Destination address,: 16 bits long. Identifies the remote and local port numbers. The length of the datagram is the total number of bytes, including the header and the data part, because the length of the header is fixed. So the domain is mainly used to calculate the variable-length data part (also known as data load) 3, the choice of protocol choice to consider three aspects: (1) The data reliability requirements for data requirements of high reliability of the application needs to select the TCP protocol, such as authentication, password field transfer is not allowed to error, In the case of data reliability, the application section chooses UDP transmission. (2) The real-time application of the TCP protocol in the transmission process to carry out three handshake, retransmission confirmation and other means to ensure the reliability of data transmission. Using the TCP protocol will have a large delayWhen Therefore, it is not suitable for applications with high real-time. such as VoIP, video surveillance and so on. In contrast, the UDP protocol can play a very good role in these applications. (3) Network reliability in the case of network conditions are not very good to choose the TCP protocol (such as WAN, etc.), but if the network condition is very good (such as LAN) select the UDP protocol to reduce network load. 4, Network BASIC Programming 4.1, Socket overview 1, socket definition in Linux network programming is done through the Stocket interface. The socket interface is a special I/O interface, which is also a file descriptor. Each socket is represented by a semi-related description {protocol, local address, local port}, and a complete socket with a related description {protocol, local address, local port, remote address, remote port}. The socket also has a function call that resembles an open file, which returns an integer socket descriptor, and subsequent connections, data transfers, and so on, are done through the socket. 2, Socket type common socket type has 3 kinds: (1) streaming socket (SOCK_STREAM) streaming socket provides a reliable, connection-oriented communication flow, it uses the TCP protocol, so as to ensure the correctness and sequencing of data transmission. (2) Datagram Socket (SOCK_DGRAM) datagram sockets define a non-connected service, which is unordered by transmitting data through separate messages. and is not guaranteed to be reliable, error-free. It uses datagram protocol UDP. (3) Raw socket RAW sockets allow direct access to underlying protocols such as IP or IGMP, which is powerful but inconvenient to use, mainly for the development of some protocols.  2.2, address and Sequence processing 1, address structure related processing (1) Data structure Introduction
The sockaddr and SOCKADDR_IN two structures are used to hold the socket information as follows: struct SOCKADDR {unsigned short sa_family;/* address family */char sa_data[14];/* A 14-byte protocol address that contains the IP address and port of the socket */}; struct SOCKADDR_IN {short NT sa_family;/* address family */unsigned Short int sin_port;/* port number */ struct IN_ADDR sin_addr;/*ip address */unsigned char sin_zero[8];/* padding 0 to keep the same size as the struct sockaddr */};
(2) Structure field
Structure header File #include
Sa_family Af_inet:ipv4 protocol
Af_inet6:ipv6 protocol
Af_local:unix Domain Protocol
Af_link: Link Address protocol
Af_key: Key socket (socket)
2. Data storage prioritization (1) function indicates that the computer data store has two byte precedence: High byte precedence and low byte priority. Data on the Internet is transmitted over the network in high order byte precedence, so in some cases it is necessary to convert this two-byte storage-priority suck to one another. Four functions: Htons, Ntohs, htonl, Ntohl. (2) function format
Required header File #include
Function prototypes uint16_t htons (uint16_t host16bit) uint32_t htonl (uint16_t host32bit) uint16_t ntohs (uint16_t net16bit) uint16_t Ntohl ( uint16_t net32bit)
Parameters Host16bit: Host byte-order 16bit data
Host32bit: Host byte-order 32bit data
Net16bit: 16bit data for network byte order
Net32bit: 32bit data for network byte order
return value Success: Returns the bytes to be converted
Failed:-1

3, address format conversion (1) function Description The user usually uses dotted decimal values when expressing an address. The usual use of socket programming is binary, which requires the conversion of these two values. The functions used here are: Inet_aton, inet_addr, and Inet_ntoa, while IPV4 and IPV6 compatible functions have Inet_pton (dotted decimal addresses are mapped to binary addresses) and inet_ IPv4. NTOP (binary address mapping is a dotted decimal address). (2) Function format Inet_pton function:
Required header File #include
Function prototypes int Inet_pton (int family,const char *strptr, void *addrptr)
Parameters FAMILY:AF_INET:IPV4 Agreement; Af_inet6:ipv6 Agreement
StrPtr: The value to convert
Addrptr: Post-conversion address
return value Success: 0
Failed:-1

Inet_ntop function:
Required header File #include
Function prototypes int inet_ntop (int family,void *addrptr, char *strptr, size_t len)
Parameters FAMILY:AF_INET:IPV4 Agreement; Af_inet6:ipv6 Agreement
StrPtr: The value to convert
Addrptr: Converted address; Len: Worth the size after the conversion
return value Success: 0
Failed:-1

4, the name Address conversion: (1) function description in Linux, there are some functions to achieve hostname and address conversion, the most common are: gethostbyname (hostname to IP), gethostbyaddr (IP address conversion without hostname), Getaddrinfo (Automatic identification of IPV4 address and IPV6 address). GETHOSTBYNAME (hostname conversion to IP) and gethostbyaddr (IP address conversion without hostname) involve a hostent structure:
struct Hostent {char *h_name;/* official host name */char **h_aliases;/* host alias */int h_addrtype;/* address type */int h_length;/* address length */char **h_ addr_list;/* an array of address pointers to IPV4 or IPV6 */}; Call this function to return information about the hostent struct. The Getaddrinfo function involves a addrinfo struct, as follows: struct addrinfo{int ai_flags;/*ai_passive,a_canonname*/int ai_family;/* address family */int Ai_socktype;/*socket type */int ai_protocol;/* protocol type */size_t ai_addrlen;/* address length */char *ai_canoname;/* hostname */struct SOCKADDR *ai_addr;/socket structure/struct addrinfo *ai_next;/* next pointer list */}
gethostbyname function:
Required header File #include
Function prototypes struct hostent *gethostbyname (const char *hostname)
Parameters Hostname: Host Name
return value Success: hostent Type pointer
Failed:-1

When you call this function, you can set the H_addrtype and h_length in the ADDRINFO structure first if Ipv4 can be set to Af_inet and 4, if IPV6 can be set to Af_inet6 and 16, if not set, the default is IPv4 address type. getaddrinfo function:

Header file #include
Function prototypes int Getaddringo (const *hostname,const char *service,const struct addrinfo *hints,struct addrinfo **result)
Parameters Hostname: Host Name
Service: server name or decimal serial string
Hints: Service lead
Result: Return results
return value Success: 0
Failed:-1

Before the call, set the hints service thread first. It is a common option value for a addrinfo structural body addrinfo structure
struct header file
Ai_flags Ai_passive: The set of interfaces is used as a passive open
Ai_canonname: Notifies getaddrinfo function to return host name
Family AF_INET:IPV protocol
Af_inet6:ipv6 protocol
Af_unspe:ipv4 or IPV6 can:
Ai_socktype Sock_stream: Byte throttle Socket socket (TCP)
SOCK_DGRAM: Datagram Socket sockets (UDP)
Ai_protocol IPPROTO_IP:IP protocol
Ipproto_ipv4:ipv4 protocol
Ipproto_ipv6:ipv6 protocol
IPPROTO_UDP:UDP protocol
IPPROTO_TCP:TCP protocol
(3) Examples of use:
/*getaddrinfo.c*/#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/ In.h> #include <sys/socket.h>int main () {struct Addrinfo hints, *res = Null;int Rc;memset (&hints,0,sizeof ( hints);/* Set addrinfo structure Parameters */hints.ai_family = Pf_unspec;hints.ai_socktype = Sock_dgram;hints.ai_protocol = IPPROTO_ udp;/* calls the getaddrinfo function */RC = getaddrinfo ("127.0.0.1", "123", &hints,&res); if (rc! = 0) {perror ("getaddrinfo"); Exit (1);} elseprintf ("Getaddrinfo success\n");} 
4.3, Socket BASIC programming (1) function description Socket programming basic functions have socket, bind, listen, accept, send, SendTo, recv, recvform these several Socket: This function is used to establish a socket connection that specifies information such as the socket type, which can be initialized to sockaddr or sockaddr_in after the socket connection is established to hold the established socket information. Bind: This function is used to bind the local IP address to the port number, and if the other address is bound to be unsuccessful, it is primarily used for TCP connections, but not necessary in connection with UDP. Connect: The function in TCP is the client side of BIND, used to establish a connection with the server, and in UDP because there is no bind function, so connect is a bit like the role of the bind function. Send and recv: These two functions are used to receive and send data, which can be repeated in TCP or in UDP. When used with UDP, it can be used after the Connect function establishes a connection. SendTo and Recvfrom: These two functions work like the Send and recv functions. When used in TCP, the following address-related parameters do not work. The function is equivalent to send and recv, and when used with UDP, the two functions can automatically look for the specified address to connect when the connection is not previously used.   Server and customer service use the TCP protocol processes such as: Server and client use UDP protocol flowchart such as: (2) function format socket function
Required header File #include
Function prototypes int socket (int family, int type, int protocol)
Parameters Family: Protocol Family Af_inet:ipv4 protocol
Af_inet6:ipv6 protocol
Af_local:unix Domain Protocol
Af_route: Routing sockets
Af_key: Key sockets
Type: Socket type Sock_stream: Byte throttle socket
SOCK_DGRAM: Datagram sockets
Sock_raw: Raw sockets
protocol:0 (except for original sockets)
return value Success: non-negative socket descriptor
Failed:-1

Bind function:
Required header File #include
Function prototypes int bind (int sockfd,struct sockaddr *my_addr, int addrlen)
Parametric prototypes SOCKFD: Socket Descriptor
MY_ADDR: Local Address
Addrlen: Address length
return value Success: 0
Failed:-1

The port number and address are given in my_addr, and if you do not specify an address, the kernel randomly assigns a temporary port to the application. Listen function:
Required header File #include
Function prototypes int listen (int socket, int backlog)
Parametric prototypes SOCKFD: Socket Descriptor
Backlog: The maximum number of requests allowed in the request queue, most system default is 20
return value Success: 0
Failed:-1
Accept function:
Required header File #include
Function prototypes int accept (int sockfd,struct sockaddr *addr,socklen_t *addrlen)
Parameters SOCKFD: Socket Descriptor
Addr: Client Address
Addrlen: Address length
return value Success: 0
Failed:-1
Connect function:
Required header File #include
Function prototypes int connect (int sockfd,struct sockaddr *serv_addr,int addrlen)
Parameters SOCKFD: Socket Descriptor
Serv_add: Server address
Addrlen: Address length
return value Success: 0
Failed:-1
The Send function:
Required header File #include
Function prototypes int send (int sockfd, const void *msg, int len, int flags)
Parameters SOCKFD: Socket Descriptor
MSG: pointer to send data
Len: Data length
Flags: typically 0
return value Success: Number of bytes Sent
Failed:-1
recv function:
Required header File #include
Function prototypes int recv (int sockfd, void *buf, int len, unsigned int flags)
Parameters SOCKFD: Socket Descriptor
BUF: Storing buffers that receive data
Len: Data length
Flags: typically 0
return value Success: Number of bytes Received
Failed:-1

Sendo function:
Required header File #include
Function prototypes int sendto (int sockfd, const void *msg,int len, unsigned int flags,const struct sockaddr *to, int tolen)
Parameters SOCTFD: Socket Descriptor
MSG: Pointer to the data to be sent
Len: Data length
Flags: typically 0
To: IP address and port information for the destination machine
Tolen: Address length
return value Success: Number of bytes Sent
Failed:-1

Recvfrom function:
Required header File #include
Function prototypes int recvfrom (int sockfd, void *buf,int len, unsigned int flags,struct sockaddr *from,int *fromlen)
Parameters SOCKFD: Socket Descriptor
BUF: Storing buffers that receive data
Len: Data length
Flags: typically 0
From: IP address and port number information for the source machine
FromTo: Address length
return value Success: Number of bytes Received
Failed:-1
(3) Examples of use
/*server.c*/#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <stdlib.h > #include <errno.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #define Servport 3333#define BACKLOG 10#define max_connected_no 10#define maxdatasize 5int Main () {struct sockaddr_in server_ Sockaddr,client_sockaddr;int Sin_size,recvbytes;int Sockfd,client_fd;char buf[maxdatasize];/* Establish socket connection */if (( SOCKFD = socket (af_inet,sock_stream,0)) = =-1) {perror ("socket"); exit (1);} printf ("Socket success! SOCKFD =%d\n ", SOCKFD);/* Set SOCKADDR_IN structure-related parameters */server_sockaddr.sin_family = Af_inet;server_sockaddr.sin_port = htons (servport); server_sockaddr.sin_addr.s_addr = Inaddr_any;bzero (& (Server_sockaddr.sin_zero), 8);/* Binding function bind*/if ( Bind (SOCKFD, (struct sockaddr *) &server_sockaddr,sizeof (struct sockaddr)) = =-1) {perror ("bind"); exit (1);} printf ("Bind success!\n");/* Call listen function */if (Listen (sockfd,backlog) = =-1) {perror ("listen"); exit (1);} printf ("ListeNing...\n ");/* Call the Accept function */if ((CLIENT_FD = Accept (SOCKFD, (struct sockaddr *) &client_sockaddr,&sin_size) = =- 1) {perror ("accept"); exit (1);} /* Call the RECV function to receive the client's request */if ((recvbytes = recv (client_fd,buf,maxdatasize,0)) = =-1) {perror ("recv"); exit (1);} printf ("Received a connection:%s\n", buf); close (SOCKFD);}

 

/*client.c*/#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h># Include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h># Define Servport 3333#define maxdatasize 100int Main (int argc,char **argv) {int Sockfd,sendbytes;char buf[maxdatasize]; struct hostent *host;struct sockaddr_in serv_addr;if (argc < 2) {fprintf (stderr, "Please enter the Sercer ' s hostname!\n" ); exit (1);} /* Address Resolution function */if ((host = (struct hostent *) gethostname (argv[1])) (==null) {perror ("GetHostName"); exit (1);} /* Create socket*/if ((SOCKFD = socket (af_inet, sock_stream,0)) = =-1) {perror ("socket"); exit (1);} /* Set SOCKADDR_IN structure-related parameters */serv_addr.sin_family = Af_inet;serv_addr.sin_port = Htons (Servport); serv_addr.sin_addr=* (( struct in_addr *) host->h_addr) bzero (& (Serv_addr.sin_zero), 8);/* Call the Connect function to initiate a connection to the server (connect */if , (struct sockaddr *) &serv_addr,sizeof (struct sockaddr)) = =-1) {perror ("connect"); exit (1);} /* Send a message to the server */if (sendbyTES = Send (SOCKFD, "Hello", 5,0)) = =-1) {perror ("send"); exit (1);} Close (SOCKFD);}

  

Network-based programming of Linux application design

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: info-contact@alibabacloud.com 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.