Redis Source Code Analysis (21)---Encapsulation of anet network communication

Source: Internet
Author: User
Tags resolve ip address

It was very easy yesterday after analyzing the Redis event-driven model, today I'll look at Anet's code, Anet is a small package of Redis for Client/server's network operations. The official interpretation of this file in the code is:

/* anet.c--basic TCP socket stuff made a bit less boring * Socket connection based on simple basic TCP
Behind the made a bit less boring what this means here, let me be a little puzzled, but the front is the focus, Basic TCP socket, based on the TCP protocol socket connection. The Anet.h API is as follows:

int Anettcpconnect (char *err, char *addr, int port); /* Default connection for TCP */int anettcpnonblockconnect (char *err, char *addr, int port); /* Non-blocking connection of TCP */int Anetunixconnect (char *err, char *path); /* anet UNIX mode default connection mode */int anetunixnonblockconnect (char *err, char *path); /* anet non-blocking connection mode for UNIX mode */int anetread (int fd, char *buf, int count); /* Anet network Read file to buffer operation */int Anetresolve (Char *err, Char *host, Char *ipbuf, size_t Ipbuf_len); /* Parse All things */int Anetresolveip (char *err, Char *host, Char *ipbuf, size_t Ipbuf_len);  /* Resolve IP address */int anettcpserver (char *err, int port, char *bindaddr, int backlog), int anettcp6server (char *err, int port, char *bindaddr, int backlog); int Anetunixserver (char *err, char *path, mode_t perm, int backlog); int anettcpaccept (char * err, int serversock, char *ip, size_t ip_len, int *port); int anetunixaccept (char *err, int serversock); int anetwrite (int f D, Char *buf, int count); /* Anet write file operation from buffer via network */int anetnonblock (char *err, int fd); /* Anet set the non-blocking method */int AnetenAbletcpnodelay (char *err, int fd); /* Enable TCP without delay */int anetdisabletcpnodelay (char *err, int fd); /* Disable TCP connection without delay */int anettcpkeepalive (char *err, int fd); /* Set TCP to maintain active connection status. Applies to all Systems */int anetpeertostring (int fd, char *ip, size_t ip_len, int *port); int anetkeepalive (char *err, int fd, int interv AL); /* Set the TCP connection to survive, to detect dead nodes, the interval option applies only to systems under Linux */int anetsockname (int fd, char *ip, size_t ip_len, int *port);
We can still see a lot of familiar methods, Read,write,accept.connect and so on in any programming language will see some of the methods. After reading this anet, the most intuitive feeling is written by the author of this network operation library is for the C language System network library, another simple package, because it is directly called library method function implementation. The author made a small package on the basis of his business needs. For example, non-blocking settings;

/* Anet set non-blocking method */int Anetnonblock (char *err, int fd) {    int flags;    /* Set the socket non-blocking.     * Note that Fcntl (2) for F_GETFL and F_SETFL can ' t is     * interrupted by a signal. */    if (flags = FCNTL (FD, F_GETFL ) = =-1) {        anetseterror (err, "Fcntl (F_GETFL):%s", Strerror (errno));        return anet_err;    }    Call the Fcntl method to set the non-blocking method    if (Fcntl (FD, F_SETFL, Flags | O_nonblock) = =-1) {        anetseterror (err, "Fcntl (f_setfl,o_nonblock):%s", Strerror (errno));        return anet_err;    }    return ANET_OK;}
The Fcntl method is a straightforward way to work. In the entire network operation file, let me feel a little bright spot or some place

(1). can set block connection or none_blocked mode of connect;

/* Default connection for TCP */int anettcpconnect (char *err, char *addr, int port) {    return Anettcpgenericconnect (err,addr,port,anet_ Connect_none);} /* Non-blocking connection for TCP */int anettcpnonblockconnect (char *err, char *addr, int port) {    return anettcpgenericconnect (ERR,ADDR, Port,anet_connect_nonblock);}
(2). can set the delay or not of the connection delay. :

/* Set whether the TCP connection is nodelay without delay */static int anetsettcpnodelay (char *err, int fd, int val) {    if (setsockopt (FD, IPPROTO_TCP, TC P_nodelay, &val, sizeof (val)) = =-1)    {        anetseterror (err, "setsockopt tcp_nodelay:%s", Strerror (errno));        return anet_err;    }    return ANET_OK;} /* Enable TCP without delay */int anetenabletcpnodelay (char *err, int fd) {    return Anetsettcpnodelay (Err, FD, 1);} /* Disable TCP connection without delay */int anetdisabletcpnodelay (char *err, int fd) {    return Anetsettcpnodelay (err, FD, 0);}
Perhaps in some cases the delay requirement is relatively high, there can be no delay.

(3). There are different processing methods for IP addresses with IPv4 and IPv6 addresses. The writer is still very thorough in his thinking. This problem is considered when resolve parsing addresses:

/* Anetgenericresolve () is called by Anetresolve () and ANETRESOLVEIP () to * does the actual work. It resolves the hostname "host" and set the string * Representation of the IP address into the buffer pointed by "ipbuf". * IF Flags is set to anet_ip_only the function only resolves hostnames * This is actually already IPv4 or IPv6 Addresse S. This turns the function * into a validating/normalizing function.                       *//* resolves a generic method that resolves a host hostname or IP address based on conditions */int anetgenericresolve (char *err, Char *host, Char *ipbuf, size_t Ipbuf_len,    int flags) {struct addrinfo hints, *info;    int RV;    memset (&hints,0,sizeof (hints));    if (Flags & anet_ip_only) hints.ai_flags = Ai_numerichost;    hints.ai_family = Af_unspec;  Hints.ai_socktype = Sock_stream;        /* Specify socktype to avoid dups *///parse hostname if (rv = getaddrinfo (host, NULL, &hints, &info))! = 0) {        Anetseterror (Err, "%s", Gai_strerror (RV));    return anet_err; }//Resolve ipV4 address by type or IPV6 address if (info->ai_family = = af_inet) {struct sockaddr_in *sa = (struct sockaddr_in *) info->ai_addr;    Inet_ntop (Af_inet, & (SA->SIN_ADDR), Ipbuf, Ipbuf_len);        } else {struct sockaddr_in6 *sa = (struct sockaddr_in6 *) info->ai_addr;    Inet_ntop (Af_inet6, & (SA->SIN6_ADDR), Ipbuf, Ipbuf_len);    } freeaddrinfo (info); return ANET_OK;}
There are some common methods that we usually use when writing code, such as the method of accept ():

/* Socket connection Operation */static int anetgenericaccept (char *err, int s, struct sockaddr *sa, socklen_t *len) {    int fd;    while (1) {    //wait through while loop to connect        FD = Accept (S,sa,len);        if (fd = =-1) {            if (errno = = eintr)                continue;            else {                Anetseterror (err, "Accept:%s", Strerror (errno));                return anet_err;            }        }        break;    }    return FD;}

Redis Source Code Analysis (21)---Encapsulation of anet network communication

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.