UNIX Network API functions (1)

Source: Internet
Author: User

Go here: http://blog.chinaunix.net/uid/23208702/abstract/1.html

1. bytecode Functions

# Include <netinet. h>

Uint16_t htons (uint16_t host16bitvalue );

Uint32_t htonl (uint32_t host32bitvalue );

Back: Network byte order value

 

Uint16_t ntohs (uint16_t net16bitvalue );

Uint32_t ntohl (uint32_t net32bitvalue );

Back: Host byte value

For a program to test the local byte sequence, see unpv12e: intro/byteorder. C.

2. byte operation functions

# Include <strings. h>

Void bzero (void * DEST, size_t nbytes );

Void bcopy (const void * SRC, void * DEST, size_t nbytes );

Int bcmp (const void * ptr1, const void * ptr2, size_t nbytes );

Return Value: 0-equal, non-0-not equal

 

# Include <string. h>

Void * memset (void * DEST, int C, size_t Len );

Void * memcpy (void * DEST, void * SRC, size_t nbytes );

Int memcmp (const void * ptr1, const void * ptr2, size_t nbytes );

Return Value: 0-the same,> 0 or <0-the same. For comparison, it is assumed that two unequal bytes are unsigned characters (unsigned char ).

3. Address Conversion Function

# Include <ARPA/inet. h>

Int inet_aton (const char * strptr, struct in_addr * addrptr );

Return Value: 1-the string is valid, and 0-the string is incorrect. ASCII to net

 

In_addr_t inet_addr (const char * strptr );

Return: if the operation succeeds, the network byte address 32 is binary. If the operation fails, inaddr_none is returned.

Char * inet_ntoa (struct in_addr inaddr );

Return Value: pointer to the point-to-decimal number string.

Int inet_ton (INT family, const char * strptr, void * addrptr );

Return Value: 1-success; 0-the input is not a valid expression format;-1-error.

Const char * inet_ntop (INT family, const void * addrptr, char * strptr, size_t Len );

Return: pointer to the result-success, null-failure.

Note:

· If the pointer of the inet_aton function is null, the function still checks the validity of the input string, but does not store any results.

· Inet_addr defect: the error returned value inaddr_none is equal to 255.255.255.255 (IPv4 finite broadcast address), so this function cannot process this address.
Try to use inet_aton instead of inet_addr.

· The execution result of the inet_ntoa function is stored in static memory and cannot be reinjected.

· The Family parameter can be af_inet or af_inet6. If the family parameter is not supported, an error occurs and errno is set to eafnosupport.

· The pointer addrptr is a structure pointer.

· Len specifies the target size to avoid Buffer Overflow. If Len is too small, a null pointer is returned, and errno is set to enospc. To help specify the size, as defined below:

# Include <netinet. h>

# Define inet_addrstrlen 16/* fro IPv4 dotted-decimal */

# Define inet6_addrstrlen 46/* for IPv6 hex string */

· The strptr parameter of the inet_ntop function cannot be a null pointer. if the pointer is successful, it is the return value of the function.

For more information about how to implement inet_ton and inet_ntop in IPv4, see unpv12e: libfree/inet_pton_ipv4.c and libfree/inet_ntop_ipv4.c.

4. readn, writen, and Readline

The function prototype is as follows:

Ssize_t readn (INT filedes, void * buff, size_t nbytes );

Ssize-T writen (INT filedes, void * buff, size_t nbytes );

Ssize_t Readline (INT filedes, void * buff, size_t maxlen );

Returned value: Number of read/write bytes,-1-error.

 

For implementation procedures, see unpv12e: lib/readn. C, lib/writen. C, lib/readline1.c, and LIB/Readline. C.

5. Test descriptor type

# Include <sys/STAT. h>

Int isfdtype (int fd, int fdtype );

Return Value: 1-indicates the specified type, 0-indicates the type, and-1-indicates an error.

 

To test whether the set interface description is child, fdtype should be set to s_ifsock.

For an implementation program of this function, see unpv12e: lib/isfdtype. c

6. Socket Functions

# Include <sys/socket. h>

Int socket (INT family, int type, int Protocol );

Return Value: non-negative descriptor-success,-1-error.

 

Family indicates the protocol family, which has the following values:

· Af_inet IPv4 protocol

· Af_inet6 IPv6 protocol

· Af_local Unix domain Protocol

· Af_route route entry interface

· Af_key key set Interface

Type specifies the set of interface types:

· Sock_stream byte stream set Interface

· Sock_dgram datagram set Interface

· Sock_raw original Interface

Protocol is generally set to 0 unless it is used on the original set interface.

 

Not all family and type combinations are valid.

Af_local is equal to the early af_unix.

7. Connect Function

# Include <sys/socket. h>

Int connect (INT sockfd, const struct sockaddr * servaddr, socklen_t addrlen );

Return Value: 0-success,-1-error.

 

Sockfd is the set interface description word returned by the socket function. servaddr and addrlen are the set interface address structure pointer and structure size pointing to the server.

You do not have to call the BIND function before calling connect.

If it is TCP, connect will trigger the TCP three-way handshake process. In the case of blocking, this function is returned only when the connection is established successfully or an error occurs,

Error:

· If you do not receive a SYN subscriber response and fail to resend it within the specified time, etimedout is returned;

· If the response to SYN subscribe is RST, it indicates that the server does not have the corresponding service on the specified port, and econnrefused is returned;

· If a destination ICMP failure occurs when the SYN is sent on the intermediate router and the request is resent within the specified time, the ehostunreach or enetunreach error is returned.

NOTE: If connect fails, the set of interfaces cannot be used any more, and must be closed. The set of interfaces cannot be called again.

8. Bind Functions

# Include <sys/socket. h>

Int BIND (INT sockfd, const struct sockaddr * maddr, socklen_t addrlen );

Return Value: 0-success,-1-error.

 

A process can bind a specific IP address to its interface, but this IP address must be an interface of the host.

For IPv4, the wildcard address is inaddr_any and its value is generally 0. The usage is as follows:

Struct sockaddr_in servaddr;

Servaddr. sin_addr.s_addr = htonl (inaddr_any );

For IPv6, the method is as follows:

Struct sockaddr_in6 serv;

Serv. sin6_addr = in6addr_any; (the system allocates the variable in6addr_any and initializes it to the constant value in6addr_any_init .)

If you want the kernel to select a temporary port, note that the BIND does not return the selected fracture value. To get a port, you must use the getsockname function.

The common error of BIND failure is eaddrinuse (the address is already in use ).

9. Listen Function

# Include <sys/socket. h>

Int listen (INT sockfd, int backlog );

Return Value: 0-success,-1-error.

 

Listen converts unconnected interfaces into passive interfaces, indicating that the kernel should accept connection requests directed to this interface. The second parameter specifies the maximum number of connections that the kernel queues for this set of interfaces.

The backlog parameter was set to the maximum value of the total number of uncompleted connection queues and completed connection queues on the listener interface, but the definition methods of different systems are different. In history, the backlog is often set to 5, however, it is not enough for busy servers; there is no common method for setting backlog, which depends on the situation, but should not be set to 0.

10. Accept Function

# Include <sys/socket. h>

Int accept (INT sockfd, struct sockaddr * cliaddr, socklen_t * addrlen );

Return Value: non-negative descriptive word-OK,-1-error.

 

ACCEPT returns the next connection from the completed connection queue header. If the completed connection queue is empty, the process goes sleep (when the interface is blocked ).

The cliaddr and addrlen parameters return the Protocol address to connect to the other party. addrlen is the value-result parameter. Before the call, the integer indicated by addrlen must be set to the length of the Set interface structure referred to by cliaddr, the returned result is modified by the kernel.

After accept is successfully executed, a connection set interface description is returned.

If you are not interested in the client's Protocol address, set cliaddr and addrlen to a null pointer.

11. Close Function

# Include <unistd. h>

Int close (INT sockfd );

Return Value: 0-OK,-1-error.

 

The default function of TCP interface close is to mark the set interface as "closed" and return it to the process immediately. This set of interface description can no longer be used by the process, but TCP will try to send any data that has been queued for sending, and then operate according to the normal TCP connection termination sequence.

Close reduces the access count of the description word by 1. When the access count is still greater than 0, close does not trigger the termination sequence of the TCP four-group connection. If you want to send a fin, you can use the shutdown function.

12. getsockname and getpeername

# Include <sys/socket. h>

Int getsockname (INT sockfd, struct sockaddr * localaddr, socklen_t * addrlen );

Int getpeername (INT sockfd, struct sockaddr * peeraddr, socklen_t * addrlen );

Return Value: 0-OK,-1-error.

 

The getsockname function returns the local Protocol address associated with the set interface.

The getpeername function returns the remote Protocol address associated with the set interface.

Addrlen is a value-result parameter.

Usage:

· For TCP customers who do not call bind, when connect returns a successful result, getsockname returns the local IP address and local port number allocated to the connection;

· After BIND is called with port number 0, use getsockname to return the local port number allocated by the kernel;

· Getsockname can be used to obtain the address family of an interface;

· On a TCP server bound with a wildcard IP address, after a connection is established, you can use getsockname to obtain the local IP address allocated to the connection;

· When a server calls exec to start, the only way to obtain the customer identity is to call the getpeername function.

13. Select Function

# Include <sys/select. h>

# Include <sys/time. h>

Int select (INT maxfdp1, fd_set * readset, fd_set * writeset, fd_set * reset tset, const struct timeval * timeout );

Return: the number of vertices in the prepared description is 0-Time-out and-1-error.

 

Definition of the timeval structure:

Struct timeval {

Long TV _sec;/* seconds */

Long TV _usec;/* microseconds */

};

Three cases of timeout values:

· Always wait: return only when I/O is ready for one descriptive word, and set timeout to a null pointer;

· Waiting for a fixed time: returns the result when I/O is prepared for a descriptive word, but does not exceed the number of seconds and microseconds specified by the timeout parameter;

· Do not wait: Check the description and return immediately. Set the number of seconds and the number of microseconds in timeout to 0.

During the waiting process, if the process captures the signal and returns it from the signal processing program, the wait is generally interrupted. For portability, select must be prepared to return an eintr error.

The timeout value is not modified by the SELECT statement (const flag) when it is returned ).

Readset, writeset, and effectset specify the descriptive words required for the kernel to test read, write, and exception conditions.

Currently, two exception conditions are supported:

1. arrival of out-of-band data of a set of interfaces;

2. The existence of control status information can be read from a pseudo-terminal master that has been set as a group.

Description set usage:

Data Type: fd_set;

Void fd_zero (fd_set * fdset );

Void fd_set (int fd, fd_set * fdset );

Void fd_clr (int fd, fd_set * fdset );

Void fd_isset (int fd, fd_set * fdset );

 

The maxfdp1 parameter specifies the number of descriptive words to be tested. Its value is the maximum descriptive word to be tested plus 1. Description word 0, 1, 2 ,..., The maxfdp1-1 is all tested.

Readset, writeset, and effectset are value-result parameters. Select modifies the descriptive word set referred to by the three parameters. Therefore, each time we call the SELECT statement, we need to set the concern position of all the descriptors to 1.

Set the interface to prepare the read conditions:

· The number of data bytes in the buffer zone received by the interface is greater than or equal to the current value in the buffer zone received by the interface. Read operations on such an interface will not be blocked and a value greater than 0 will be returned (that is, the amount of data to be read ). You can use the set interface option so_rcvlowat to set the low tide limit. For TCP and UDP, the default value is 1;

· The read half of the connection is closed (the TCP connection that receives the fin ). Read operations on such an interface will not be blocked and 0 (that is, the file Terminator) will be returned)

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.