Linux TCP socket program analysis

Source: Internet
Author: User

/************************

The server end of TCP socket communication written in C language.

Can continuously listen to the port specified by myprot

The upstream stream received by the print port.

The header file is enclosed in quotation marks because the angle brackets are escaped.

************************/

# Include "stdio. H"

# Include "stdlib. H"
# Include "errno. H"
# Include "string. H"

# Include "sys/types. H"

# Include "netinet/in. H"
# Include "sys/socket. H"
# Include "sys/Wait. H"

Int main (INT argc, char ** argv)
{
Int sockfd, new_fd;
Struct sockaddr_in my_addr;
Struct sockaddr_in their_addr;
Unsigned int sin_size, myport, listnum;
Myport = 9785; // The bound port number.
Listnum = 10;
/*************************************** **********
Socket interface: it is an API of the TCP/IP network. The SOCKET interface defines many functions and can
Develop TCP/IP network programming on the Internet on this basis

Create socket: int socket (INT domain, int type, int protoco );

Argument Description: domain indicates all protocol families, usually pf_inet (TCP/IPv4)
Of course, he can also support IPv6 and more network protocols.
Select a specific application
Type: sock_stream (TCP), sock_dgram (UDP), sock_raw
(Allow the program to use the underlying protocol)
Protolol is usually assigned "0"

Return Value: the socket descriptor is a pointer to the internal data structure. It points to the descriptor table.
Portal. When the socket function is called, the socket execution body establishes a socket,
In fact, "Creating a socket" means allocating storage for a socket Data Structure
Storage space. The socket execution body manages the descriptor table for you.
**************************************** **********/
If (sockfd = socket (pf_inet, sock_stream, 0) =-1)
{
Perror ("socket is error/N ;");
Exit (1 );
}
My_addr.sin_family = pf_inet; // specify the protocol family.

/*************************************** ************
There are two types of computer data storage priorities: high byte priority and low
Bits take precedence. Data on the internet is prioritized by high bytes in the Network
Therefore, data is stored in Low-byte-first mode internally.
To convert the data transmitted over the Internet. Otherwise
Data inconsistency occurs.
Htonl (): converts 32-bit values from the host's byte order to the network's byte order
Htons (): converts 16-bit values from the host's byte order to the network's byte order
Ntohl (): converts 32-bit values from the network byte order to the host byte order.
Ntohs (): converts 16-bit values from the network byte order to the host byte order.
**************************************** ************/
My_addr.sin_port = htons (myport); // if the value is set to 0, the system selects a random port.

My_addr.sin_addr.s_addr = inaddr_any; // enter the local IP address.
Bzero (& (my_addr.sin_zero), 0 );

/*************************************** ***********
Int BIND (INT sockfd, const struct sockaddr * my_addr, socklen_t addrlen );
Description: Create a socket and bind it to the port. It indicates that the socket is used and no one else occupies the port.

Argument Description: sockfd: Socket descriptor returned by the Socket System Call
My_addr: the address to be bound to the socket,
Is a variable similar to the following struct
Struct sockaddr {
Sa_family_t sa_family;
Char sa_data [14];
}
Return Value: 0 is returned when execution is successful. -1, error message set for errno
**************************************** ***********/
If (BIND (sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr) =-1)
{
Perror ("Bind is error/N ");
Exit (1 );
}

/*************************************** ***********
Int listen (INT sockfd, int listensum)
Description: The listen () function enables the socket to be in passive listening mode,
Create an input data queue for the socket
The received service request is stored in this queue until the process
Process them sequentially.
Argument Description: sockfd: Socket descriptor returned by the Socket System Call
Listensum: the maximum number of requests allowed in the Request queue.
Return Value: 0 is returned when execution is successful. -1, error message set for errno
**************************************** ***********/
If (Listen (sockfd, listnum) =-1)
{
Perror ("Listen is error/N ");
Exit (1 );
}
Printf ("start to listen/N ");
While (1)
{
Sin_size = sizeof (struct sockaddr_in );

/*************************************** ********************
Int accept (INT sockfd, void * ADDR, int * addrlen)
Description: The accept () function allows the server to receive client connection requests.
After the input queue is established, the server calls accept.
Function, then sleep and wait for the customer's connection request.
Argument Description: sockfd: Socket descriptor returned by the Socket System Call
ADDR: Usually a pointer to the sockaddr_in variable,
This variable is used to store the master node that initiates the connection request service.
Server Information (a host sends this request from a port)
Addrten: Usually a pointing Value
Sizeof (struct sockaddr_in) integer pointer variable
Return Value:-1 is returned for failure, and error message is set for errno.
If the socket monitored by the accept function receives the connection request,
The socket execution body will create a new socket
The row body connects the new socket to the address of the Request connection process.
The initial socket that receives the service request is still available.
To continue listening on the previous socket, you can also
Data transmission on the new socket Descriptor
**************************************** ***********************/
If (new_fd = accept (sockfd, (struct sockaddr *) & their_addr, & sin_size) =-1)
{
Perror ("accept is error/N ");
Continue;

}
Printf ("server: Got connection from % s/n", inet_ntoa (their_addr.sin_addr ));

Char * P;
Char sock_buf [1024];
Bzero (FIG, 1024 );
P = sock_buf;
Int rval = 0;

/*************************************** ***********************************
Int Recv (socket S, char far * Buf, int Len, int flags );
Both the client and server applications use the Recv function to receive data from the other end of the TCP connection.

The first parameter of this function specifies the receiver socket descriptor;

The second parameter specifies a buffer that is used to store the data received by the Recv function;

The third parameter specifies the length of the Buf;

The fourth parameter is usually set to 0.

Only the execution process of the Recv function for Synchronous socket is described here. When the application calls the Recv function, the Recv waits for the data in the s sending buffer to be transmitted by the Protocol.
It is suggested that a network error occurs when data in the sending buffer of the transmitted S, the Recv function returns socket_error. If no data is in the sending buffer of s or the data is successfully sent by the protocol
Then, Recv checks the receiving buffer of socket S. If there is no data in the receiving buffer or the Protocol is receiving data, the Recv waits until the data is received by the Protocol. When the Protocol
After the data is received, the Recv function copies the data in the s receiving buffer to the Buf. (Note that the data received by the protocol may be larger than the Buf length. Therefore, you need to call the data several times in this case.
The Recv function can copy the data in the s receiving buffer. The Recv function is only used to copy data, and the protocol is used to actually receive data.) The Recv function returns the actual copy
The number of bytes. If a Recv error occurs during copy, socket_error is returned. If the Recv function is interrupted while waiting for the Protocol to receive data, 0 is returned.
**************************************** ***********************************/

If (rval = Recv (new_fd, P, 1024, 0) <0)
{
Printf ("Recv errror/N ");
}
Else
{
Printf ("Recv % s/n", P );
}
/*************************************** ***********************************
Fork a sub-process runs ********************************* in parallel for this connection with the parent process **************************** **************************************** *******/
If (! Fork ())
{

/*************************************** ********************************
Int send (INT sockfd, const void * MSG, int Len, int flags)
Description: sends information to the client through a sub-process.
Argument Description: sockfd: the socket descriptor you want to use to transmit data
MSG: a pointer to the data to be sent.
Len: the length of data in bytes.
Flags: usually set to 0 (this parameter involves blocking and non-blocking issues)
**************************************** ********************************/
If (send (new_fd, "Hello, huhan/N", 14,0) =-1)
{
Perror ("send is error/N ");
Close (new_fd );
Exit (0 );
}
}

/*************************************** ***************************************
After all the data operations are completed, you can call the close () function to release the socket and stop
Any data operations on the socket

For example, you can close the write operation of a socket and allow the socket to continue to accept data until all data is read.

Int Shutdown (INT sockfd, int how );

Sockfd is the descriptor of the socket to be closed. The how parameter allows you to select the following methods for the shutdown operation:
· 0 ------- you are not allowed to continue receiving data.
· 1 ------- data cannot be sent again
· 2 ------- you are not allowed to send or receive data.
If the shutdown operation succeeds, 0 is returned. If an error occurs,-1 is returned and the corresponding errno is set.
**************************************** ***************************************/
Close (new_fd );

/*************************************** *************************************
Pid_t waitpid (pid_t PID, int * stat_loc, int option)
The PID parameter specifies the PID of the child process to be waited for. If it is-1, waitpid will return the information of any child process, and
Like wati (), if stat_loc is not a null pointer, waitpid writes the status information to the position pointed. Option
The parameter allows us to change the waitpid's behavior. The most useful option is wnohang, which prevents
The waitpid () call suspends the invocation of the caller. You can use this option to check whether a child process has ended.
The execution will continue.
**************************************** *************************************/
Waitpid (-1, null, wnohang );
}
}

 

Client Program:

# I nclude <stdlib. h>

# I nclude <stdio. h>

# I nclude <errno. h>

# I nclude <string. h>

# I nclude <netdb. h>

# I nclude <sys/types. h>

# I nclude <netinet/in. h>

# I nclude <sys/socket. h>

Int main (INT argc, char * argv [])

{

Int sockfd;

Char buffer [1024];

Struct sockaddr_in server_addr;

Struct hostent * Host;

Int portnumber, nbytes;

If (argc! = 3)

{

Printf ("Usage: % s hostname portnumber/A/N", argv [0]);

Exit (1 );

}

/* Gethostbyname
You can obtain the host's
IP
Address
*/

If (host = gethostbyname (argv [1]) = NULL)

{

Printf ("gethostname error/N ");

Exit (1 );

}

/* Portnumber
Is the port number
*/

If (portnumber = atoi (argv [2]) <0)

{

Printf ("Usage: % s hostname portnumber/A/N", argv [0]);

Exit (1 );

}

/*
Customer Program Creation started
Sockfd
Descriptor
*/

If (sockfd = socket (af_inet, sock_stream, 0) =-1)

{

Printf ("socket error: % S/A/N", strerror (errno ));

Exit (1 );

}

/*
The customer program fills in the data on the server.
*/

Bzero (& server_addr, sizeof (server_addr ));

Server_addr.sin_family = af_inet;

/*
Host byte order to network byte order
*/

Server_addr.sin_port = htons (portnumber );

Server_addr.sin_addr = * (struct in_addr *) Host-> h_addr );

/*
Client Program initiates Connection Request
*/

If (connect (sockfd, (struct sockaddr *) (& server_addr ),

Sizeof (struct sockaddr) =-1)

{

Printf ("Connect error: % S/A/N", strerror (errno ));

Exit (1 );

}

/*
Connection successful
*/

If (nbytes = read (sockfd, buffer, 1024) =-1)

{

Printf ("read error: % s/n", strerror (errno ));

Exit (1 );

}

Buffer [nbytes] = '/0 ';

Printf ("I have received: % s/n", buffer );

/*
End communication
*/

Close (sockfd );

Exit (0 );

}



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.