"UNIX Network Programming" overview

Source: Internet
Author: User
Tags socket error htons

It is generally believed that a Web server program is a long (background) running program (that is, daemons, daemon), such programs are initialized in the form of a process, the name of the daemon program usually ends with the letter "D", such as httpd. Typically a customer-initiated request simplifies the protocol and the program itself, and some complex network applications require asynchronous callback (asynchronous callback) communication, where the server initiates request information to the customer.

In a multi-tasking computer operating system,Daemon Process(English:DaemonEnglish pronunciation:/ d i? m ?n /or English pronunciation: / d e? m ?n /) is a computer program that executes in the background. Such programs are initialized in the form of a process. The name of the daemon program usually ends with the letter "D": for example, syslogd refers to the daemon that manages the system log.

Typically, the daemon does not have any parent processes (that is, ppid=1) that exist, and is directly under Init at the UNIX system process level. A daemon program usually makes itself a daemon by running a fork on a child process and then immediately terminating its parent process so that the child process can run under init. This method is often referred to as "shelling".

The system usually starts the daemon together at startup. The daemon provides support for responding to network requests, hardware activities, and so on, or other requests to other applications through certain tasks. Daemons can also configure hardware (such as DEVFSD on some Linux systems), run scheduled tasks (such as Cron), and run other tasks.

In a DOS environment, this type of application is called a resident program (TSR). In Windows systems, the role of the daemon is performed by an application called a Windows service.

In the original Mac OS system, such applications are called "extensions". Mac OS x, as Unix-like, has daemons. (There are also "services" in Mac OS X, but they are conceptually different from similar programs in Windows.) )

Book on page 5th of the program, time to get the client program:

#include"Unp.h"intMain (intargcChar**argv) {    intSOCKFD, N; CharRecvline[maxline +1]; structsockaddr_in servaddr; if(ARGC! =2) Err_quit ("usage:a.out <IPaddress>"); if(SOCKFD = socket (af_inet, Sock_stream,0)) <0) Err_sys ("Socket Error"); Bzero (&AMP;SERVADDR,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port= Htons ( -);/*Daytime Server*/    if(Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <=0) Err_quit ("Inet_pton error for%s", argv[1]); if(Connect (SOCKFD, (SA *) &servaddr,sizeof(SERVADDR)) <0) Err_sys ("Connect Error");  while((n = Read (SOCKFD, Recvline, MAXLINE)) >0) {Recvline[n]=0;/*null Terminate*/        if(Fputs (recvline, stdout) = =EOF) Err_sys ("fputs Error"); }    if(N <0) Err_sys ("Read Error"); Exit (0);}

Use the premise is need to have Unp.h, configuration method Touch Me

Main steps:

    1. Create a TCP socket SOCKFD = socket (af_inet,sock_stream, 0);
      The socket function creates a socket that represents the Internet (AF_INET,IPV4 protocol, if V6 is Af_inet6) byte stream (SOCK_STREAM,TCP). The return value is a small integer (int) descriptor, and all subsequent function calls use that descriptor to identify the socket, and the return value-1 indicates an error
    2. Specify the IP address and port number of the server
      Empty the contents of the struct (bzero), htons (int) indicates that the conversion port is short, Inet_pton is an upgrade of inet_addr, supports IPV6, and is used to convert dotted decimal into binary, such as 127.0.0.1 0xff000001
    3. Establish a connection to the server
      Incoming socket descriptor, server address struct, server address structure body length
    4. Read-In and output server response
      Using the Read function to read the server's answer, TCP is a byte-stream protocol that does not have a record boundary (the number of bytes sent at a time varies). When the amount of data is large, there is no guarantee that a read can return the entire answer to the server, so when reading data from a TCP socket, it is written in while (>0) when Read returns 0 (indicating that the connection is closed) or negative (error) is terminated. As you can see, n indicates the length of the returned record, so recvline[n] = 0; refers to the add terminator (TCP itself does not provide a record end flag) for easy output.
    5. Terminating programs
      Exit terminates the program, and UNIX closes all open descriptors of the process while it terminates the process, and the TCP socket is then closed

Define parcel Functions (wrapper function), the first letter capitalized, to help the code concise, can implement error handling.

The following is a package function to write a time to get the server program:

#include"Unp.h"#include<time.h>intMain (intargcChar**argv) {    intLISTENFD, CONNFD; structsockaddr_in servaddr; CharBuff[maxline];    time_t ticks; LISTENFD= Socket (Af_inet, Sock_stream,0); Bzero (&AMP;SERVADDR,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_addr.s_addr=htonl (Inaddr_any); Servaddr.sin_port= Htons ( -);/*Daytime Server*/Bind (LISTENFD, (SA*) &servaddr,sizeof(SERVADDR));    Listen (LISTENFD, Listenq);  for ( ; ; ) {CONNFD= Accept (LISTENFD, (SA *) NULL, and NULL); Ticks=Time (NULL); snprintf (Buff,sizeof(Buff),"%.24s\r\n", CTime (&ticks));        Write (CONNFD, Buff, strlen (buff));    Close (CONNFD); }}

Main steps:

  1. Create a TCP socket
  2. Bundle the address (the server port that is used to connect to other clients) to the socket
    Inaddr_any represents any (but only one network card) network interface
    Inaddr_any is the address specified as 0.0.0.0, which in fact represents an indeterminate address, or "all addresses", "arbitrary addresses". In general, each system is defined as a value of 0.
    in general, if you are setting up a Web server application, you should notify the server operating system: Listen on a port yyyy on an address xxx.xxx.xxx.xxx and send packets to me with the heard data. This process, you are done through the bind () system call. -that is, your program will bind to an address on the server, or share population a port on a server's address as used. The server operating system can give you this specified address, or you can not. If your server has multiple network cards (with different IP addresses on each network card), and your service (whether listening on UDP ports or listening on TCP ports), for some reason: Your server operating system may increase or decrease the IP address at any time, It is also possible to avoid the trouble of determining what network Port (NIC) is on the server--you can tell the operating system when you call Bind (): "I need to listen on the YYYY port, all the ports that are sent to the server, regardless of which network card/IP address received the data, I handled it." "At this point, the server program listens on the 0.0.0.0 address.

  3. Switch the socket to a listening socket (this socket is designed to allow external connections to be accepted by the kernel)
    The 3 call steps for sockets, bind, and listen are normal steps for any TCP server to prepare the "listener descriptor (listening descriptor, in this case, LISTENFD)". Listenq is defined in Unp.h, which specifies the maximum number of client connections that the system kernel allows to queue on this listener descriptor.
  4. Accepts a client connection (a TCP three handshake, and returns a new descriptor for the user who connects to the server), sends an answer
    The server process is put to sleep in the accept call, waiting for a client connection to arrive and accepted by the kernel (this step is "establishing a TCP connection"), the TCP connection uses the so-called "three-time handshake" to establish the connection, and the accept returns when the handshake is complete, and the return value is called the "Connected descriptor" ( Connected descriptor) "New descriptor (CONNFD), which is used to communicate with the newly connected customer.
  5. Terminating the connection (TCP four waves)
    Close (CONNFD) causes a TCP connection termination sequence: One fin is sent in each direction, and each fin is confirmed by its respective peer.

"UNIX Network Programming" overview

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.