List of common socket Functions

Source: Internet
Author: User
Tags set socket

Conversion functions

IP address Conversion Function:

Unsigned long inet_addr (const char * CP );

Inet_addr converts a dot-decimal IP address string to a 32-bit IP address (Network byte order ).

Char * inet_ntoa (struct in_addr in );

Inet_ntoa converts a 32-bit IP address into a dotted-decimal IP address string.

 

These two functions are inverse functions.

 

Byte sequence Conversion:

Htons () -- "host to network short"

Htonl () -- "host to network long"

Ntohs () -- "network to host short"

Ntohl () -- "network to host long"

 

Network Connection Functions

Initialize sock Connector:

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

The function returns the socket descriptor.-1 indicates an error.

The domain parameter can only be set to af_inet. The Protocol parameter is generally set to 0.

Application Example:

TCP mode: sockfd = socket (af_inet, sock_stream, 0 );

UDP mode: sockfd = socket (af_inet, sock_dgram, 0 );

 

Bind Port:

Int BIND (INT sockfd, struct sockaddr * Sa, int addrlen );

-1 indicates an error. The most common error is that the port has been bound by another program.

Note: in Linux systems, ports lower than 1024 can only be bound to programs with root permissions.

 

Connect to the network(For TCP mode ):

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

If the function returns-1, an error occurs, which may be caused by connection timeout or access failure. If 0 is returned, the connection is successful and data can be transmitted through sockfd.

 

Listening port(For TCP mode ):

Int listen (INT sockfd, int queue_length );

Call the BIND () function to bind sockfd to a port. Otherwise, the system specifies a random port.

Receiving queue: the connection request of a new client is first placed in the receiving queue until the server program calls the accept function to accept the connection request.

The second queue_length parameter indicates the length of the receiving queue, that is, the maximum number of connection requests allowed before the server program calls the accept function. Redundant connection requests will be rejected.

 

Response Connection Request(For TCP mode ):

Int accept (INT sockfd, struct sockaddr * ADDR, int * addrlen );

The accept () function will respond to the connection request, establish a connection, and generate a new socket descriptor to describe the connection. This connection is used to exchange information with a specific client.

The function returns the socket descriptor of the new connection, and the error returns-1.

After the function is called, the ADDR will be filled in with the address information of the connection peer, such as the Peer IP address and port.

Addrlen is used as a parameter to indicate the size of the ADDR memory zone. After the function returns, it is filled with the size of the returned ADDR structure.

Accept is a blocking function by default, blocking until a connection request exists.

Application Example:

Struct sockaddr_in their_addr;/* used to store the address information of the connection peer */
Int sin_size = sizeof (struct sockaddr_in );

... ... (Call socket (), BIND (), listen () and other functions in sequence)

New_fd = accept (sockfd, & their_addr, & sin_size );
Printf ("peer address: % s/n", inet_ntoa (their_addr.sin_addr ));

... ...

 

Disable socket connection:

Int close (INT sockfd );

Closing the connection will interrupt the read and write operations on the socket.

Disabling the socket descriptor for listen () will disable connection requests from other clients.

 

Partially disable socket connection:

Int Shutdown (INT sockfd, int how );

The shutdown () function can interrupt connections unilaterally, that is, prohibit information transmission in a certain direction.

Parameter how:

0-forbidden to receive information
1-Forbidden message sending
2-receiving and sending are both prohibited, and the effect is the same as that of the close () function.

 

Socket round robin Selection:

Int select (INT numfds, fd_set * readfds, fd_set * writefds, fd_set * limit TFDs, struct timeval * timeout );

Used in Multi-Channel Synchronous I/O mode (this will be explained in detail in synchronous working mode)





Fd_zero (* Set) clears the socket set
Fd_set (S, * Set) adds s to the socket set
Fd_clr (S, * Set) Remove s from the socket set
Fd_isset (S, * Set) determines whether s is in the socket set

Constant fd_setsize: Maximum number of elements in a set

 

Waiting for selection mechanism:

Int poll (struct pollfd * ufds, unsigned int NFDs, int timeout );

It is a variant of the select mechanism and is used in multi-channel synchronous I/O mode (this will be explained in detail in synchronous working mode)

Ufds is an array of the pollfd structure. The number of elements in the array is NFDs.

     struct pollfd {           int fd;           /* file descriptor */           short events;     /* requested events */           short revents;    /* returned events */       };

 

 

Receive/send messages:

TCP Mode:

Int send (int s, const void * Buf, int Len, int flags );

Int Recv (int s, void * Buf, int Len, int flags );

The function returns the number of bytes actually sent/received. The value-1 indicates an error. You need to disable this connection.

The function is blocked by default until the sending/receiving process is complete or an error occurs.

Note: If the return value of the send function is not the same as the Len parameter, the remaining unsent information needs to be sent again.

 

UDP:

Int sendto (int s, const void * Buf, int Len, int flags, const struct sockaddr * To, int tolen );

Int recvfrom (int s, void * Buf, int Len, int flags, struct sockaddr * From, int * fromlen );

Difference from TCP:

Specify the recipient of the sent/received data (fifth parameter to/from)

The function returns the number of bytes actually sent/received. The value-1 indicates an error.

The function is blocked by default until the sending/receiving process is complete or an error occurs.

Note: If the return value of the send function is not the same as the Len parameter, the remaining unsent information needs to be sent again.

 

Message-based approach:

Int sendmsg (int s, const struct msghdr * MSG, int flags );

Int recvmsg (int s, struct msghdr * MSG, int flags );

Send/receive a message. The message uses the following data structure:

Struct msghdr {

Void * msg_name;/* optional address */

Socklen_t msg_namelen;/* size of address */

Struct iovec * msg_iov;/* scatter/gather array */

Size_t msg_iovlen;/* # elements in msg_iov */

Void * msg_control;/* ancillary data, see below */

Socklen_t msg_controllen;/* ancillary data buffer Len */

Int msg_flags;/* flags on received message */

};

This method can be either connection-oriented or connectionless. It is flexible but not commonly used. The workflow will be explained in the following program example (network simulation device.

 

Flag Space:

The preceding six sending/receiving functions have a flags parameter to indicate the data sending/receiving flag. Common flags include:

Msg_peek is valid for the data receiving function, indicating that read data is not cleared after network data is read.

Msg_waitall is valid for the data receiving function, indicating that it is executed until the Buf is fully read, socket errors, or the program receives signals.

Msg_dontwait is valid for the data sending function, indicating that the function will return directly instead of blocking the data after it is sent. (Valid only for non-blocking socket)

Msg_nosignal is valid for the sending and receiving function, indicating that an error occurs after the connection is closed but the sigpipe signal is not sent to the program.

MSG_OOB is valid for both sending and receiving, indicating to read/write out-of-band data)

 

Out-of-band data instance Diagram

 

Obtain/set socket parameters or information

Obtain the local host name:

Int gethostname (char * hostname, size_t size );

Save the host name to the hostname.

 

Obtain local information:

Int getsockname (INT sockfd, struct sockaddr * ADDR, int * addrlen );

ADDR contains the returned host information.

Example:

Struct sockaddr_in SA;

Int Len = sizeof (SA );

Getpeername (sockfd, (struct sockaddr *) & SA, & Len );

Printf ("local IP: % s", inet_ntoa (SA. sin_addr ));

 

 

Obtain information about the target host.:

Int getpeername (INT sockfd, struct sockaddr * ADDR, int * addrlen );

ADDR contains the returned host information.

Example:

Struct sockaddr_in SA;

Int Len = sizeof (SA );

Getpeername (sockfd, (struct sockaddr *) & SA, & Len );

Printf ("peer IP: % s", inet_ntoa (SA. sin_addr ));

 

Obtain DNS information:

Struct hostent * gethostbyname (const char * Name );

Struct hostent * gethostbyaddr (const char * ADDR, int Len, int type );

Returns a pointer to struct hostent, which is defined as follows:

Struct hostent {

Char * h_name;/* official name of Host */

Char ** h_aliases;/* alias list */

Int h_addrtype;/* Host address type */

Int h_length;/* length of address */

Char ** h_addr_list;/* list of addresses */

};

# Define h_addr h_addr_list [0]/* for backward compatibility */

How to obtain DNS information will be detailed in the subsequent program snippets.

The error handling during DNS operations is different from that in normal programs. gethostbyname indicates the error number by setting h_errno. The corresponding error functions include hstrerror () and herror (), which correspond to strerror () and perror.

Obtain or change the socket property:

Int getsockopt (INT sockfd, int level, int name, char * value, int * optlen );

Int setsockopt (INT sockfd, int level, int name, char * value, int * optlen );

For socket programming, the level is generally a constant sol_socket

Name attribute type, value attribute parameter, and optlen attribute memory block Length

Commonly used:

So_rcvtimeo, so_sndtimeo: Get or set the timeout for sending/receiving through socket.

So_sndbuf, so_rcvbuf: gets or sets the buffer size for socket sending/receiving.

So_broadcast: gets or sets the socket status so that it can broadcast and send datagram. (It can only be used in UDP mode ).

So_reuseaddr: Set the port bound to the socket to be reused.

Note: in Linux, if a socket is bound to a port, the socket is normally closed or the program exits, and the port remains bound for a period of time, other programs (or the original program restarted) cannot bind the port. You can avoid this problem by calling the following statement:

Opt = 1;
Len = sizeof (OPT );
Setsockopt (sockfd, sol_socket, so_reuseaddr, & OPT, & Len );

 

Obtains or modifies the I/O attribute of a socket.:


Int IOCTL (INT sockfd, long cmd, unsigned long * argp );

CMD attribute type, which is a parameter of the argp attribute.

Commonly used:

Fionread: the number of bytes of unread data in the socket buffer.

Fionbio: When argp is set to zero, it is in blocking mode. If it is not set to zero, it is not in blocking mode.

Siocatmark: checks whether unread out-of-band data exists (for TCP only), returns true or false

 

Int fcntl (int fd, int cmd, long Arg );

F_setfl: When ARP is set to o_nonblock, it enters the non-blocking mode. When ARP is set to 0, it enters the blocking mode.

F_getfl to obtain attributes.

Http://www.aka.org.cn/Lectures/002/Lecture-2.1.8/Lecture-2.1.8/new_page_6.htm

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.