5.2. socket () --- get the file descriptor
I don't want to talk about it for a long time-I want to call the system function socket (). The following is his prototype:
# Include <sys/types. h>
# Include <sys/socket. h>
Int socket (intdomain, int type, int protocol );
But what about these parameters? Which socket does they allow you to use (IPv4 or IPv6; TCP or UDP ).
It was once hard-coded by people, and you can do the same. (For domain, you can select PF_INET or PF_INET6; for type, you can select SOCK_STREAM or SOCK_DGRAM; SET protocol to 0, or you can call getprotobyname () to find the protocol you want, "tcp" or "UDP ".)
Note: SOCK_STREAM is equivalent to TCP; SOCK_DGRAM is equivalent to UDP. So you don't have to pay twice for another J
(The editor described the relationship between PF _ * and AF _ * here)
Note: they are actually equivalent. If you are interested, you can read "AF_xxxVersus PF_xxx" in Chapter 4, Section 2nd of UnixNetwork Programming"
What you really need to do is to directly use the result value obtained by calling getaddrinfo () to the socket () function as follows:
Int s;
Struct addrinfohints, * res;
// Do the lookup
// [Pretend wealready filled out the "hints" struct]
Getaddrinfo (www.example.com, "http", & hints, & res );
// [Again, youshoshould do error-checking on getaddrinfo (), and walk
// The "res" linked list looking for valid entries instead of just
// Assuming thefirst one is good (like sums of these example do .)
// See the sectionon client/server for real examples.]
S = socket (res-> ai_family, res-> ai_socktype, res-> ai_protocol );
The socket () function simply returns a socket descriptor for use by other system functions, or returns the-1 error. The global variable errno is set with an error value. (For details about errno, see the man documentation)
Good, good, good! But what are the benefits of using this method? The answer is: Concise!
From the column xiaobin_HLJ80