Simple use and encapsulation of socket in Linux
/*
* File function: Simplified socket operation function in Linux
* File name: linux_socket.h
* Created on: July 15, July 19, 2007
* Creator: wlzqi
* Language: c Or C ++ Language
* Environment: Linux + windows
* Function requirements:
* + Relatively low-level functions
* + Only system APIs and C libraries are used, and no third-party libraries are used.
* + Global variables cannot be used.
* + Frequent use
* + Modular (functions are not nested)
* + Strong and efficient
* + Local tests must be performed.
* + Do not use dynamic memory allocation whenever possible (you can add it with caution in special cases)
* + All variables must be byte aligned
*CodeRequirements:
* + Minimize temporary variables
* +AlgorithmTo be refined
* + The temporary variable name must start with an English or an English abbreviation or an English phrase and be accurate (no more than 12 letters)
* + The function name must clearly describe the function, and _ is used to connect words. For example: analyze_string,
* Execute the SQL statement execute_ SQL and get_database_field_name to obtain the database field name...
* + All functions Use lowercase letters for spelling.
* + Symbol, and; followed by a space, Symbol & * The variable to be next to the right, symbol ++ variable to the left, all operators
* Spaces must be left on both sides.
* + If, for, where, and so on must be adjacent to '(' There is a space between the symbols
* + Clear and easy-to-read code can be exercised properly using null
* Annotation style:
* + The annotations should be appropriate and the style should be unified.
* + Annotations can only be used on code (only /* */ ) And peers (available // And /**/ ) Two Styles
* + If the comment and code are in the same direction, two tabs must be left blank.
* + There must be a space between the comments and comments.
* + If the comment needs to be written by a branch, it must look like the following:
*/*
** Comment content
** Comment content
** */
* + Function comments must include function descriptions, parameter descriptions, return descriptions, precautions, and examples.
* Note:
* + If the functions in this file are the same as those of system functions
* + 'Required' to ensure that no warning is generated during compilation.
* + By default, data is sent to a disconnected (invalid) address.ProgramWill exit, so we recommend that you do not use the default
* Default settings. It is recommended that the application process the sigpipe signal as needed. At least do not use the default processing method.
* The default processing method of the system is to exit the process, which makes it difficult for your application to investigate why the process exits.
* If signal (sigpipe, sig_ign) is called, the program will return-1 when the other party is disconnected and the errno is epipe (32)
* If signal (sigpipe, function_name) is called, the program will first respond to the sigpipe function when the other party is disconnected, then return-1, and errno is epipe (32)
* If the recipient is disconnected during data transmission, the sender will first return the number of data bytes that have been sent, and-1 will be returned when the next call is sent. errno is econnreset (104)
* It is recommended to use signal to process signals to prevent inexplicable process exit and descriptor leakage and dead connections.
* Added modules:
* + Socket_format_err format the socket error message
* + Socket_format_herr custom formatting socket error message
* + Socket_create create socket
* + Socket_connect connects to socket
* + Socket_bind: Specify the local port
* + Socket_listen listens to the local port Descriptor
* + Et_accept accepts socket connections
* + Socket_send send data packet
* + Socket_recv receives data packets
* + Socket_send_pack package and send data packets
* + Socket_recv_pack receives packaged data packets
* + Close_socket close socket
**/
# Ifndef linux_socket_h _
# Define linux_socket_h _
# Include <sys/socket. h>
# Include <sys/types. h>
# Include <netinet/in. h>
# Include <unistd. h>
# Include <ARPA/inet. h>
# Include <netdb. h>
# Include <signal. h>
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Define the socket variable */
Typedef int socket;
# Ifndef Boolean
# Define Boolean
/* Define a Boolean variable */
Typedef Enum Boolean {false, true} bool;
# Endif
# Ifndef false
# Define false (0)
# Endif
# Ifndef true
# Define true (! False)
# Endif
/* Define a Boolean variable */
# Ifndef boollean
# Define boollean
Typedef int bool;
# Endif
/* Define null characters */
# Ifndef null
# Define null 0
# Endif
/*---------------------------------------------------------------------------*/
/* Function: format the socket error message.
* Parameter description: None
* Return Description: Return Error description text
* Note:
* Example:
**/
Char * socket_format_err ()
{
Return (char *) hstrerror (h_errno );
}
/*---------------------------------------------------------------------------*/
/* Function: Customize the formatting socket error message
* Parameter description: The pszerr text to be added before the system error message description
* Return Description: None
* Note:
* Example: socket_format_herr ("warning ");
* Output warning: XXXX .....
**/
void socket_format_herr (const char * pszerr)
{
herror (pszerr );
}
/* functions */
/* function Functions: socket creation
* parameter description: ntimer received timeout (seconds ), 0 indicates unlimited
* ntimes sending timeout (seconds), 0 indicates unlimited
* return description: -1 indicates that the request failed. Otherwise, the created socket
* Notes: port rebinding is used in the function
* example: 1 . socket_create (af_inet, sock_stream, ipproto_tcp, 10, 10) TCP
* 2 . socket_create (af_inet, sock_dgram, ipproto_ip, 0, 0) UDP
**/
socket socket_create (const int NaF, const int ntype, const int nprotocol, const int ntimes, const int ntimer)
{
static socket m_sock;
# Ifndef Win32
Struct timeval TV;
# Endif
M_sock =-1;
M_sock = socket (NaF, ntype, nprotocol );
If (m_sock =-1) Return-1;
# Ifdef Win32
Ntimes * = 1000;
Ntimer * = 1000;
/* Sending time limit */
If (setsockopt (m_sock, sol_socket, so_sndtimeo, (char *) & ntimes, sizeof (INT) <0)
Return-1;
/* Receiving time limit */
If (setsockopt (m_sock, sol_socket, so_rcvtimeo, (char *) & ntimer, sizeof (INT) <0)
Return-1;
# Else
TV. TV _usec = 0;
TV. TV _sec = ntimes;
/* Sending time limit */
If (setsockopt (m_sock, sol_socket, so_sndtimeo, & TV, sizeof (TV) <0)
Return-1;
TV. TV _sec = ntimer;
/* Receiving time limit */
If (setsockopt (m_sock, sol_socket, so_rcvtimeo, & TV, sizeof (TV) <0)
Return-1;
# Endif
Return m_sock;
}
/*---------------------------------------------------------------------------*/
/* Function: connect to socket
* Parameter description: Socket socket
* Pcszip IP
* Nport
* Return Description: false indicates a failure.
* Note:
* Example: 1 . Socket socke;
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 0, 0) =-1 ){
*
* Return false;
*}
* If (socket_connect (socke, "192.168.12.111", 9000) = false) return false;
**/
Bool socket_connect (const Socket socket, const char * pcszip, const unsigned nport)
{
Struct sockaddr_in svraddr;
Svraddr. sin_family = af_inet;
Svraddr. sin_addr.s_addr = inet_addr (pcszip );
Svraddr. sin_port = htons (nport );
If (connect (socket, (struct sockaddr *) & svraddr, sizeof (svraddr) =-1) return false;
Return true;
}
/*---------------------------------------------------------------------------*/
/* Function: Specify the local port to the descriptor.
* Parameter description: nport must be a local port.
* Return Description: false indicates a failure.
* Note:
* Example:
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 0, 0) =-1 ){
*
* Return false;
*}
* If (socket_bind (socke, 9000) = false) return false;
**/
Bool socket_bind (const Socket socket, const unsigned nport)
{
Int nopt = 1;
Struct sockaddr_in svraddr;
Svraddr. sin_family = af_inet;
Svraddr. sin_addr.s_addr = inaddr_any;
Svraddr. sin_port = htons (nport );
If (setsockopt (socket, sol_socket, so_reuseaddr, (char *) & nopt, sizeof (nopt) <0) return false;
If (BIND (socket, (struct sockaddr *) & svraddr, sizeof (svraddr) =-1) return false;
Return true;
}
/*---------------------------------------------------------------------------*/
/* Function: listens to the local port Descriptor
* Parameter description: nbacklog sets the maximum length of the Request queue, which is usually 5
* Return Description: false indicates a failure.
* Note:
* Example:
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 0, 0) =-1 ){
*
* Return false;
*}
* If (socket_bind (socke, 9000) = false) return false;
* If (socket_listen (socke, 5) = false) return false;
**/
Bool socket_listen (const Socket socket, const int nbacklog)
{
If (Listen (socket, nbacklog) =-1) return false;
Return true;
}
/*---------------------------------------------------------------------------*/
/* Function: accept socket connections
* Parameter description: pszcliip [out] peer IP Address
* Return Description: The client socket descriptor is returned successfully. Otherwise,-1 is returned.
* Note:
* Example:
* Socket m_sock;
* Char szcliip [16];
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 0, 0) =-1 ){
*
* Return false;
*}
* If (socket_bind (socke, 9000) = false) return false;
* If (socket_listen (socke, 5) = false) return false;
* Memset (szcliip, 0, 16 );
* M_sock = socket_accept (socke, szcliip );
**/
Socket socket_accept (const Socket socket, char * pszcliip)
{
Static socket m_sock;
Struct sockaddr_in cliaddr;
Socklen_t addrlen = sizeof (cliaddr );
M_sock = accept (socket, (struct sockaddr *) & cliaddr, & addrlen );
If (m_sock =-1) Return-1;
If (pszcliip! = NULL) sprintf (pszcliip, "% s", inet_ntoa (cliaddr. sin_addr ));
Return m_sock;
}
/*---------------------------------------------------------------------------*/
/* Function: Send a socket package
* Parameter description: Socket socket
* Pszbuff buffer to be sent
* Nlen length of the package to be sent
* Return Description:-1 indicates a failure. Otherwise, the number of actually sent bytes is returned.
* Note: nflags are generally 0.
* Example: 1 . Socket socke;
* Char szbuff [512];
* Memset (szbuff, 0,512 );
*
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 0, 0) =-1 ){
*
* Return false;
*}
* If (socket_connect (socke, "192.168.12.111", 9000) = false) return false;
* // Copy the bytes to be sent to the buffer
* Socket_send (socke, szbuff, strlen (szbuff), 0 );
**/
Int socket_send (const Socket socket, const char * pszbuff, const int nlen, const int nflags)
{
Int nbytes = 0;
Int ncount = 0;
While (ncount <nlen ){
Nbytes = Send (socket, pszbuff + ncount, nlen-ncount, nflags );
If (nbytes <= 0 ){
Return-1;
}
Ncount + = nbytes;
}
Return ncount;
}
/*---------------------------------------------------------------------------*/
/* Function: receives the socket package
* Parameter description: Socket socket
* Pszbuff buffer to be received
* Nlen length of the package to be received
* Return Description:-1 indicates a failure. Otherwise, the number of actually received bytes is returned.
* Note: nflags are generally 0.
* Example: 1. Socket socke;
* Char szbuff [512];
* Memset (szbuff, 0,512 );
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 10) =-1 ){
*
* Return false;
*}
* If (socket_connect (socke, "192.168.12.111", 9000) = false) return false;
* // Copy the bytes to be sent to the buffer
* Socket_send (socke, szbuff, strlen (szbuff), 0 );
* Socket_recv (socke, szbuff, strlen (szbuff), 0 );
**/
Int socket_recv (const Socket socket, char * pszbuff, const int nlen, const int nflags)
{
Return Recv (socket, pszbuff, nlen, nflags );
}
/*---------------------------------------------------------------------------*/
/* Function: Package and send the socket package
* Parameter description: Socket socket
* Pszbuff buffer to be sent
* Nlength_all total length of the package to be sent
* Unpack_size the number of bytes sent at a time
* Return Description:-1 indicates a failure. Otherwise, the number of actually sent bytes is returned.
* Note:
* Example: 1 . Socket socke;
* Char szbuff [512];
* Memset (szbuff, 0,512 );
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 10) =-1 ){
*
* Return false;
*}
* If (socket_connect (socke, "192.168.12.111", 9000) = false) return false;
* // Copy the bytes to be sent to the buffer
* Socket_send_pack (socke, szbuff, strlen (szbuff), 512 );
**/
Unsigned long socket_send_pack (const Socket socket, const char * pszbuff, const unsigned long nlength_all, const unsigned unpack_size)
{
Int nlength = 0;
Long naddlengths = 0;
While (naddlengths <nlength_all ){
If (nlength = socket_send (socket, pszbuff + naddlengths, unpack_size, 0) <0 ){
Break;
}
Naddlengths + = nlength;
}
Return naddlengths;
}
/*---------------------------------------------------------------------------*/
/* Function: receives and packs a socket package.
* Parameter description: Socket socket
* Pszbuff buffer to be received
* Nlength_all total length of the package to be received
* Unpack_size the number of bytes received at a time
* Return Description:-1 indicates a failure. Otherwise, the number of actually received bytes is returned.
* Note:
* Example: 1 . Socket socke;
* Char szbuff [512];
* Memset (szbuff, 0,512 );
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 10) =-1 ){
*
* Return false;
*}
* If (socket_connect (socke, "192.168.12.111", 9000) = false) return false;
* // Copy the bytes to be sent to the buffer
* Socket_send_pack (socke, szbuff, strlen (szbuff), 512 );
* Socket_recv_pack (socke, szbuff, 2048,512 );
**/
Int socket_recv_pack (const Socket socket, char * pszbuff, const unsigned long nlength_all, const unsigned unpack_size)
{
Int nlength = 0;
Unsigned long naddlengths;
Naddlengths = 0;
While (naddlengths <nlength_all ){
If (nlength = socket_recv (socket, pszbuff + naddlengths, unpack_size, 0) <0 ){
Break;
}
Naddlengths + = nlength;
}
Return naddlengths;
}
/*---------------------------------------------------------------------------*/
/* Function: Disable socket
* Parameter description: Socket socket
* Return Description: false indicates a failure. Otherwise, the number of actually received bytes is returned.
* Note:
* Example: 1 . Socket socke;
* Char szbuff [512];
* Memset (szbuff, 0,512 );
*
* If (socke = socket_create (af_inet, sock_stream, ipproto_tcp, 10) =-1 ){
*
* Return false;
*}
* If (socket_connect (socke, "192.168.12.111", 9000) = false) return false;
* // Copy the bytes to be sent to the buffer
* Socket_send_pack (socke, szbuff, strlen (szbuff), 512 );
* Socket_recv_pack (socke, szbuff, 2048,512 );
* Socket_close (socke );
**/
Bool socket_close (const Socket socket)
{
Return close (socket) = 0? True: false;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
# Endif/* linux_socket_h _*/