Socket API
1. Byte order
The network protocol uses "big-end byte order" (the high-order byte of the starting address store) to transmit these multi-byte integers.
# include
Uint16_t htons (uint16_t host16bitvalue)
Uint32_t htonl (uint32_t host32bitvalue)
Uint16_t ntohs (uint16_t net16bitvalue)
Uint32_t ntohl (uint32_t net32bitvalue)
two。 Translating IPv4 addresses between dotted decimal ASCII code strings and 32-bit network byte-ordered binary values
[/ / the following two functions are eliminated and written to help transition memory
# include
/ / return 1 if the string is valid, otherwise 0
/ / insufficient: addrptr returns INADDR_NONE (32-bit 1) when there is an error, and some manual says it returns-1
Int inet_aton (const char * strptr, struct in_addr * addrptr)
Char* inet_ntoa (struct in_addr inaddr); / / insufficient: non-reentrant
]
/ / advantages: both ipv4 and ipv6 are suitable
/ / p:presentation n:numeric
# include
/ / Note: 1 is returned for success, 0 for invalid input format, and-1 for error EAFNOSUPPORT
Int inet_pton (int family, const char * strptr, void * addrptr)
/ / A pointer to the result is returned successfully, and NULL; ENOSPC is returned if an error occurs.
Const char* inet_ntop (int family, const void * addrptr, char* strptr, size_t len)
3. Socket
# include
Int socket (int family, int type, int protocol)
Int connect (int sockfd, const struct sockaddr* servaddr, socklen_t addrlen)
/ / bind can specify an IP address or port, or both, or neither.
/ / bind system reserved port, root permission is required
Int bind (int sockfd, const struct sockaddr* myaddr, socklen_t addrlen)
/ / return the local protocol address associated with the socket
Int getsockname (int sockfd, struct sockaddr* localaddr, socklen_t * addrlen)
/ / return the remote protocol address associated with the socket, such as the corresponding address of the customer sockfd returned by accept
Int getpeername (itn sockfd, struct sockaddr* peeraddr, socklen_t addrlen)
Int listen (int sockfd, int backlog); / / still don't understand what value backlog specifies is better?
The listening socket maintains two queues: the incomplete connection queue (SYN_RCVD) and the completed connection queue (ESTABLISHED).
Int accept (int listenfd, struct sockaddr* cliaddr, socklen_t * addrlen)
4. After the connection is established
# include
Int close (int sockfd)
/ *
Fork is called once and returned twice: the calling process returns the child process ID number, and the child process returns 0
There are two uses of fork: one is that a process creates a copy of itself, and the other is that a process wants to execute another program, and the copy calls exec to replace itself with a new program.
, /
Pid_t fork (void)
Pid_t getppid (void); / / get the parent process ID