TCP socket Programming instance code for Windows and Linux

Source: Internet
Author: User
Tags bind function prototype local time new set sprintf htons

The code under Windows is as follows

Server.cpp #include  <iostream> #include  <windows.h> #define  IP  "127.0.0.1" #
define port 8888 #pragma  comment (lib, "Ws2_32.lib") using namespace std;
Char* gettime (); Int main () {    WSADATA wsaData;     WORD Ret;      if  ((Ret = wsastartup (Makeword (2, 2),  &wsadata)  != 0) )     {        cout <<  "WSAStartup (
)  error whit: " << Ret << endl;
        wsacleanup ();
        return -1;
    }//the unified version type.
    SOCKET sockSer, sockCli;
    sockser = socket (af_inet,sock_stream,0);
    SOCKADDR_IN addrSer, addrCli;     addrser.sin_family = af_inet;
    addrser.sin_port = htons (port);     addrser.sin_addr. S_un.
S_ADDR = INET_ADDR (IP);
    int len = sizeof (SOCKADDR);
    bind (sockser,  (sockaddr*) &addrser, len);//bind socket.
    listen (sockser,5)/monitor.
    cout <<  "The server is waiting for a connection ..."  << endl;
    sockcli = accept (sockser,  (sockaddr*) &addrcli, &len);     if  (sockcli == -1)     {         cout <<  "Accept ()  error with:"  << sockcli
 << endl;
        closesocket (SOCKCLI);
        closesocket (Sockser);         wsacleanup ();
    }     char serbuff[255];
    string s;     while  (1)     {       
 recv (Sockcli,serbuff,sizeof (Serbuff), 0);
        send (Sockcli,gettime (), 30, 0);
    }     wsacleanup ();
    closesocket (Sockser);
    closesocket (SOCKCLI);
    return 0; } char* gettime () {    char buff[255];     systemtime sys
;//windows the following system time call.
    getlocaltime (&sys);//Initialize local time.     sprintf (Buff, "%d:%d:%d:%d:%d:%d", Sys.wyear,sys.wmonth,sys.wday,sys.whour,sys.wminute,
Sys.wsecond);
    return buff; }
Client.cpp #include  <iostream> #include  <windows.h> #define  PORT 8888 #define
 IP  "127.0.0.1" using namespace std; #pragma  comment (lib, "Ws2_32.lib") Int main () {    DWORD Ret;   
  WSAData wsaData;     if  ((Ret = wsastartup (Makeword (2, 2),  &wsadata)  !=  0)     {        cout << "WSAStartup
()  Error Wiht :  "<< Ret << endl;
        wsacleanup ();
        return -1;    &NBSP}     socket sockcli = socket (AF_INET,SOCK_STREAM,0)
;
    SOCKADDR_IN addrSer;
    addrSer.sin_family = AF_INET;     addrser.sin_port = htons (port);     addrser.sin_addr. S_un.
S_ADDR = INET_ADDR (IP);
    //does not require binding monitoring.
    int ret = connect (SOCKCLI, (sockaddr*) &addrser,sizeof (SOCKADDR));     if  (ret != 0)     {     
   cout <<  "Client Connection failed ..."  << endl;
        closesocket (SOCKCLI);
        wsacleanup ();
        return -1;    &NBSP}     else     {     
   cout <<  "Customer service side Connection successful ..."  << endl;
   &NBSP}     const char timebuff[] =  "Times:";
    char serbuff[255];     while  (1)     {        send (
Sockcli,timebuff,strlen (Timebuff) +1,0);
        recv (Sockcli,serbuff,sizeof (Serbuff), 0);
        //gets the local time of the server.         cout <<timebuff<<serbuff << 
Endl
        sleep (2000);
    }     return 0; }


The following code for Linux is as follows:

Makefile

CLI=CLI
ser=ser
dir=.
cc=g++
ser_obj=$ (dir)/ser.o
cli_obj=$ (dir)/cli.o ser_src=$
(dir)/ser.cpp cli_src=$
(dir)/cli.cpp
all:$ (CLI) $ (SER)
. Phony:all
$ (SER): $ (ser_obj)
@$ (cc)-O $@ $^
$ (CLI): $ (cli_obj)
@$ (cc)-O $@ $^
$ (ser_obj): $ (SER_SRC)
@$ (cc)-C $<
$ (cli_obj): $ (CLI_SRC)
@$ (cc)-C $<
. Phony:clean clean
:
@rm $ (DIR)/*.O $ (SER) $ (CLI)



Ser.cpp

#include &nbsp;&lt;iostream&gt; #include &nbsp;&lt;sys/socket.h&gt; #include &nbsp;&lt;arpa/inet.h&gt; #include &nbsp;&lt;string.h&gt; #include &nbsp;&lt;netinet/in.h&gt; #define &nbsp;port&nbsp;8888 #define &nbsp;IP&nbsp; "
127.0.0.1 "using&nbsp;namespace&nbsp;std; Int&nbsp;main () {&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;sockSer,sockCli; &nbsp;&nbsp;&nbsp;&nbsp;sockaddr_in&nbsp;
ADDRSER,ADDRCLI;
&nbsp;&nbsp;&nbsp;&nbsp;sockser&nbsp;=&nbsp;&nbsp;socket (af_inet,sock_stream,0);
&nbsp;&nbsp;&nbsp;&nbsp;addrSer.sin_family&nbsp;=&nbsp;AF_INET;
&nbsp;&nbsp;&nbsp;&nbsp;addrser.sin_port&nbsp;=&nbsp;htons (port);
&NBSP;&NBSP;&NBSP;&NBSP;ADDRSER.SIN_ADDR.S_ADDR&NBSP;=&NBSP;INET_ADDR (IP);
&nbsp;&nbsp;&nbsp;&nbsp;socklen_t&nbsp;len&nbsp;=&nbsp;sizeof (SOCKADDR);
&nbsp;&nbsp;&nbsp;&nbsp;bind (Sockser, (sockaddr*) &amp;addrser,len);
&nbsp;&nbsp;&nbsp;&nbsp;listen (sockser,5);
&nbsp;&nbsp;&nbsp;&nbsp;cout&lt;&lt; "I&nbsp;am&nbsp;waiting ..." &lt;&lt;endl; &nbsp;&nbsp;&nbsp;&nbsp;sockcli&nbsp;=&nbsp;accept (Sockser, Sockaddr*) &amp;addrcli,&amp;len); &nbsp;&nbsp;&nbsp;&nbsp;if (sockcli==-1) &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;close (sockSer); &nbsp;
&nbsp;&nbsp;&nbsp;close (SOCKCLI);
&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;-1;
&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;clibuff[255]; &nbsp;&nbsp;&nbsp;&nbsp;while (1) &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;recv (
Sockcli,clibuff,sizeof (Clibuff), 0);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout&lt;&lt;clibuff&lt;&lt;endl; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (strncmp ("Quit", clibuff,4) ==0) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout&lt;&lt; "I&nbsp;am&nbsp;quit&nbsp;too!"
&lt;&lt;endl;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send (SockCli, Clibuff,strlen (Clibuff) +1,0);&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nBsp;&nbsp;close (SOCKCLI);
&nbsp;&nbsp;&nbsp;&nbsp;close (Sockser);
&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;0; }



//cli.cpp

#include &nbsp;&lt;iostream&gt; #include &nbsp;&lt;string.h&gt; #include &nbsp;&lt;sys/socket.h&gt; #include &nbsp;
&lt;netinet/in.h&gt; #include &nbsp;&lt;arpa/inet.h&gt; using&nbsp;namespace&nbsp;std; #define &NBSP;PORT&NBSP;8888 #define &nbsp;IP&nbsp; "127.0.0.1" Int&nbsp;main () {&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;
Sockcli&nbsp;=&nbsp;socket (af_inet,sock_stream,0);
&nbsp;&nbsp;&nbsp;&nbsp;sockaddr_in&nbsp;addrSer;
&nbsp;&nbsp;&nbsp;&nbsp;addrSer.sin_family&nbsp;=&nbsp;AF_INET;
&nbsp;&nbsp;&nbsp;&nbsp;addrser.sin_port&nbsp;=&nbsp;htons (port);
&NBSP;&NBSP;&NBSP;&NBSP;ADDRSER.SIN_ADDR.S_ADDR&NBSP;=&NBSP;INET_ADDR (IP);
&nbsp;&nbsp;&nbsp;&nbsp;socklen_t&nbsp;len&nbsp;=&nbsp;sizeof (SOCKADDR);
&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;ret&nbsp;=&nbsp;connect (SOCKCLI, (sockaddr*) &amp;addrser,len); &nbsp;&nbsp;&nbsp;&nbsp;if (ret!=0) &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;cout&lt;&lt; "Connect ()
&nbsp;erorr&nbsp;with&nbsp;: "&lt;&lt;ret&lt;&lt;endl;
&nbsp;&nbsp;&nbsp;&nbsp;close (SOCKCLI); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;-1;
&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;serbuff[255]; &nbsp;&nbsp;&nbsp;&nbsp;while (1) &nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cin&gt;&gt;
Serbuff;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send (Sockcli,serbuff,strlen (Serbuff) +1,0); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (strncmp ("Quit", serbuff,4) ==0) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&NBSP} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;memset (Serbuff, ' a ', sizeof (Serbuff));&nbsp;&nbsp;&nbsp;&nbsp;
&NBSP;&NBSP;&NBSP;&NBSP} &nbsp;&nbsp;&nbsp;&nbsp;close (SOCKCLI);
&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;0; }



Linux-based TCP network programming


A. Linux under the TCP programming framework


The process of programming a TCP network consists of two modes of server and client. Server mode creates a service program that waits for the client user's connection, receives the user's connection request, and processes it according to the user's request; The client mode connects to the destination server's address and port, sends the request to the server, and processes the server's response.

1. Server-side programs include

Ø set up socket (socket ())

Ø Sockets and Port bindings (BIND ())

Ø set the server's listening connection (listen ())

Ø Receive Client connection (accept ())

Ø Receive and send data (send (), recv ())

Ø closing sockets (Close ())

2. Notes

In the 1> socket initialization process, the options for sockets are determined based on the user's need for sockets. The socket () function is set according to the user-defined network type, protocol type and specific protocol label parameters. The system generates a socket file descriptor for users to use, depending on the needs of the user.

2> sockets are bound to an address structure during the binding process of a socket to a port. After binding, parameters such as IP address and port address and protocol type that the socket represents are manipulated according to the binding value.

3> because a server needs to meet multiple client connection requests, and the server can handle only a limited number of client connection requests at a time, the server needs to set the length of the server-side queued queues.

4> after the client sends a connection request, the server needs to receive the client's connection before other processing can take place.

5> you can read data from a socket file descriptor or send data to a file descriptor after the server receives a client request. After receiving the data, the server processes the data according to the defined rules and sends the results to the client.

6> when the server is finished processing data, to end the communication process with the client, you need to turn off the socket connection

2. Client programs include

Ø set up socket (socket ())

Ø Connecting server (Connect ())

Ø Read and write network data (send (), recv ())

Ø closing sockets (Close ())

3. Server-side and client program differences

The difference between a client program and a server-side program is that the client can connect to the server side instead of the address binding after the socket is established.

There are listen () and accept () two functions on the server side, and the client does not need these two functions.

Two. Linux based TCP socket function

1. Socket

1> function Prototype:

int socket (int domain,int type,int protocol)

2> function Function:

The function socket () is used to create a socket descriptor.

3> Parameters:

Ødomain: Specifies the protocol family to use for creating sockets, in header files

Defined in. Sometimes the pf_inet is used in the program, and the Af_inet and pf_inet values are the same in the header file.

The common protocol families are as follows:

Af_unix: Creates a socket that communicates only within the machine.

Af_inet: Using the IPV4TCP/IP protocol

AF_INET6: Using the IPV6 TCP/IP protocol

Description

Af_unix can only be used for single UNIX system interprocess communication, while Af_inet is for interne and thus allows communication between remote hosts. It is generally assigned to af_inet.

Øtype: Specifies the type of socket communication, corresponding to the following parameters

Sock_stream: Creating a TCP stream socket

Sock_dgram: Creating a UDP datagram socket

Sock_raw: Create original socket

Øprotocol: Specifies a specific type of protocol

The parameter protocol is typically set to 0, which indicates the protocol used to determine the socket type specified by the protocol family and parameter type specified in parameter domain. When you are a raw socket, the system cannot uniquely determine the protocol, and you need to use this parameter to specify the protocol used.

4> return value: Returns a newly created socket after successful execution, and returns one-1 if an error occurs, and the error code is stored in errno.

5> Example: Call the socket function to create a UDP socket

int sock_fd;
SOCK_FD = socket (af_inet,sock_dgram,0);
if (sock_fd< 0) {
perror ("socket");
Exit (1);
}

2. Bind

1> function Prototype:

int bind (int sockfd,struct sockaddr *my_addr,socklen_t addrlen)

2> function function

The function bind () binds a socket file descriptor to the address and port.

3> Parameters:

ØSOCKFD:SOCKFD is the file descriptor that invokes the return of the socket function;

Øaddrlen is the length of the SOCKADDR structure.

ØMY_ADDR: is a pointer to the SOCKADDR structure that holds the address of the local socket (that is, the port and IP address) information. However, due to system compatibility problems, this structure is not used in general, and another structure (STRUCTSOCKADDR_IN) is used instead

4> Socket Address Structure:

(1) struct sockaddr:

The structure struct SOCKADDR defines a generic socket address that is

Defined in Sys/socket.h.

struct sockaddr{

unsigned short sa_family;/* address type, af_xxx*/

char sa_data[14];/*14 byte protocol address */
  }

A. Sin_family: Represents the address type, and for network programming using the TCP/IP protocol, this value can only be af_inet.

B. Sa_data: Store the specific protocol address.

(2) sockaddr_in

Each protocol family has its own protocol address format, and the TCP/IP protocol group address format is a struct struct sockaddr_in, which is defined in the Netinet/in.h header file.

structsockaddr_in{

unsigned short sin_family;/* address type * *

unsigned short sin_port;/* port number/

struct IN_ADD R SIN_ADDR;/*IP Address */

unsigned char sin_zero[8];/* padding byte, general assignment to 0*/

}

A. Sin_family: Represents the address type, and for network programming using the TCP/IP protocol, this value can only be af_inet.

B. Sin_port: is the port number

C. SIN_ADDR: Used to store 32-bit IP addresses.

D. Array Sin_zero is a filled field with a general assignment of 0.

E. struct IN_ADDR is defined as follows:

structin_addr{
unsigned long s_addr;
}

The length of the structure body sockaddr is 16 bytes, and the sockaddr_in length of the structure is 16 bytes. You can set the parameter my_addr sin_addr to Inaddr_any instead of a certain IP address to bind to any network interface. For a computer with only one IP address, inaddr_any corresponds to its IP address; for multihomed hosts (with multiple network adapters), Inaddr_any indicates that the server program will process connection requests from the corresponding ports on all network interfaces

5> return Value:

The function returns 0 when a failure occurs, and 1 when there is an error, and the error code is stored in errno.

6> Example: Call the socket function to create a UDP socket

struct SOCKADDR_IN addr_serv,addr_client;/* Local address information * *
memset (&serv_addr,0,sizeof (structsockaddr_in));
addr_serv.sin_family= af_inet;/* Protocol Family * *
addr_serv.sin_port= htons (serv_port);//Local port number/*
Addr_serv.sin_ Addr.s_addr= htonl (Inaddr_any);
//////////////////////////* Socket binding/if (Bind (SOCK_FD, structsockaddr *) &addr_serv), sizeof (struct sockaddr_in))       
{
perror ("bind");
Exit (1);
}

3. Monitor local port Listen ()

1> function function: function listen () is used to initialize the server to connect the queue, the server processing client connection request is sequential processing, at the same time can only handle a client connection. When multiple client connection requests arrive at the same time, the server is not processed concurrently, but the client connection request that cannot be processed is placed in the wait queue, which is defined by the listen () function.

2> function Prototype:

#includ
int Listen (int sockfd,int backlog);

3> Formal parameters

ØSOCKFD:SOCKFD is the file descriptor returned by calling the socket function

Øbacklog: Specifies the maximum length of the connection queue. If the connection queue has reached its maximum, subsequent connection requests are rejected by the server. Most systems are set to 20 and can be modified to 5 or 10, depending on the system's affordability or application requirements.

4> return value: When the Listen () function runs successfully, the return value is 0, and when the run fails, its return value is-1, and the error code is stored in errno.

Example of the 5>.listen () function:

 #define &NBSP;SERV_PORT&NBSP;3000 Int main (int argc,char * Argv[]) {int sock_fd; struct sockaddr_in addr_serv,addr_client;/* Local address information * * sock_fd = 
Socket (af_inet,sock_dgram,0); if (sock_fd< 0) {       perror ("socket");     
   exit (1);
} memset (&serv_addr,0,sizeof (structsockaddr_in)); addr_serv.sin_family= af_inet;/* Protocol Family/Addr_serv.sin_port= htons (serv_port);/* Local Port number */Addr_serv.sin_ Addr.s_addr= htonl (inaddr_any);  /* any local address/* socket binding////if (Bind Sock_fd, (structsockaddr *) &addr_
Serv), sizeof (struct sockaddr_in))  <0) {       perror ("bind");
       exit (1);
}//Set the length of the server listening queue if (Listen (sock_fd,5)  <0) {       perror ("listen");
       exit (1); }



4. Accept (receive a network request)

1> function Function:

When a client's connection request reaches the port on which the server host listens, the client's connection waits in the queue, knowing that the server handles the receive request.

After the function accept () is successfully executed, a new set of interface file descriptors is returned to indicate the client's connection, and the client connection information can be obtained by this new descriptor. As a result, when the server successfully processes the client's request connection, there will be two file descriptors, the old file descriptor representing the client's connection, and the function send () and recv () to send and receive data through the new file descriptor.

2> function Prototype:

#include
#include
int accept (int sock_fd,struct sockaddr*addr,socklen_t *addrlen);

3> Formal parameters

ØSOCK_FD: A listening socket that is created by a function socket, bound to a local port by a function bind, and then transformed by a function listen.

ØADDR: The address and port used to hold the host that initiated the connection request.

Øaddrlen is the size of the structure that the addr points to.

4> return value: The return value of the Accept () function is a newly connected client socket file descriptor that communicates with the client through a new socket file descriptor returned by accept (), rather than by a file descriptor when the socket is established. If an error occurs in the Accept () function, accept () returns-1, and the error value can be obtained by errno.

5> if the socket specified by the parameter sock_fd is set to block (default mode under Linux), and the connection request queue is empty, accept () is blocked until there is a connection request, and if the socket specified by parameter s is set to non-blocking, if the queue is empty, Accept will immediately return -1,errno is set to Eagain.

6> instance:

int client_fd;
int Client_len;
struct sockaddr_in client_addr;
Client_len = sizeof (struct sockaddr_in);
CLIENT_FD = Accept (sock_fd, (struct sockaddr *) &client_addr,&client_len);
if (conn_fd< 0) {
perror ("accept");
Exit (1);
}

5. Connect (Connect target network server)

1> function Function:

After a socket is established, the client can connect directly to the server without the need for address binding. The function to connect to the server is connect (), which connects the server with the specified parameters, such as IP address, port number.

In the case of TCP programming, the Connect () function is used for the server to issue a connection request, and the server's IP address and port number are specified by the parameter serv_addr.

In the case of UDP programming, the Connect function does not establish a true connection, it simply tells the kernel the destination address (specified by the second parameter) that communicates with the socket, and only data sent from that destination address is received by that socket. The advantage of calling the Connect function is that you do not have to specify the destination address each time you send and receive data.

2> function Prototype:

#include
#include
int connect (int sock_fd,struct sockaddr *serv_addr,socklen_taddrlen);

3> Parameters:

ØSOCK_FD: The socket file descriptor that is returned when the socket is established, calling the socket () returned.

ØSERV_ADDR: is a pointer to the data structure sockaddr, which includes the destination IP address and port number of the server to which the client needs to connect.

Øaddrlen: Indicates the size of the second parameter, you can use sizeof (struct sockaddr)

4> after successful execution returns 0, error occurs return-1, error code is stored in errno.

5> instance:

int sock_fd;
struct sockaddr_in serv_addr;
if ( -1 = = (SOCK_FD = = socket (af_inet,sock_stream,0)) {
printf ("Error:unable to Createsocket (%i) ... \ n", errno);
Perror ("sockets");
Exit (1);
}
memset (&serv_addr,0,sizeof (structsockaddr_in));
serv_addr.sin_family= af_inet;
serv_addr.sin_port= htons (dest_port);
Serv_addr.sin_addr.s_addr= inet (dest_ip_address);
if ( -1== connect (sock_fd, struct sockaddr *) &serv_add,sizeof (struct
sockaddr)) {
printf ("Error: Unable to the establishconnection to socket (%i) ... \ n ", errno);
Perror ("socks");
Close (SOCK_FD);
Exit (1);
}

6. Send (sending data)

1> function: The function send is used to send data on a TCP socket, and send can be used only for sockets that are in a connected state.

2> function prototype

#include
#include
ssize_t send (int conn_fd,const void *msg,size_t len, int flags);

3> function Parameters:

ØCONN_FD: A socket descriptor that is returned after the Accept () function is invoked for a socket descriptor that has already been established.

Ømsg: A buffer that holds the data sent.

Ølen: The length of the send buffer

Øflags: For control options, generally set to 0, or take the following values:

²msg_oob: To send Out-of-band data (Out-of-band data) on a specified socket, a socket of that type must support Out-of-band data (such as: Sock_stream).

²msg_dontroute: Sends data through the most direct path, ignoring routing settings for downlevel protocols.

4> return Value:

The execution returns the number of bytes that actually sent the data, and an error returns-1, and the error code is stored in errno.

Execution success simply indicates that the data is written to the socket in a buffer and does not indicate that the data has been successfully sent over the network to the destination.

5> instance:

#define BUFFERSIZE 1500
char send_buf[buffersize];
..... if (send (conn_fd,send_buf,len,0) < 0) {
perror ("send");
Exit (1);
}

7. recv (Receive data)

1> function: recv () is used to receive data on a TCP socket. function recv receives data from the specified socket descriptor and saves it to the specified buf.

2> function prototype

#include
#include
ssize_t recv (int conn_fd,void *buf,size_t len,int flags);

3> function Parameters:

ØCONN_FD: The socket descriptor that is returned after the Accept () function is invoked for a socket descriptor that has already been established.

ØBUF: Receive Buffer

Ølen: The size of the receive buffer

Øflags: For control options, generally set to 0 or take the following values

²msg_oob: Request to receive Out-of-band data

²msg_peek: View data only and not read

²msg_waitall: Returns only when the receive buffer is full.

4> function return value

The function execution successfully returns the number of data bytes received, Error returns 1, and the error code is stored in errno.

5> instance:

#define BUFFERSIZE 1500
char recv_buf[buffersize];
..... if (recv (conn_fd,recv_buf,sizeof (RECV_BUF), 0) < 0) {
perror ("recv");
Exit (1);
}

8. Close

1> function Prototype:

int close (int fd);

2> function Function:

Function Close is used to turn off a socket descriptor.

3> function Parameters:

Ø parameter FD is a socket descriptor.

4> return Value:

Execution successfully returns 0, error returns-1. The error code is stored in errno.

Description: The header file for the close () function is #include.

Three. Linux based TCP socket programming instance

1. The instance program is divided into the server side and the client, the client sends Hello Tigerjibo to the server side, and the total number of strings received is sent to the client after the server receives the string;


2. Server-side programs:



&nbsp;&nbsp;1&nbsp; #include &lt;stdio.h&gt; &nbsp;&nbsp;2&nbsp; #include &lt;stdlib.h&gt; &nbsp;&nbsp;3&nbsp;# include&lt;string.h&gt; &nbsp;&nbsp;4&nbsp; #include &lt;errno.h&gt; &nbsp;&nbsp;5&nbsp; &nbsp;&nbsp;6&nbsp; &nbsp; &nbsp;7&nbsp; #include &lt;sys/types.h&gt; &nbsp;&nbsp;8&nbsp; #include &lt;sys/socket.h&gt; &nbsp;&nbsp;9&nbsp;# Include&lt;unistd.h&gt;//close () &nbsp;10&nbsp; #include &lt;netinet/in.h&gt;//struct&nbsp;sockaddr_in &nbsp;11 &nbsp; #include &lt;arpa/inet.h&gt;//inet_ntoa &nbsp;12&nbsp; #define &NBSP;&NBSP;QUEUE_LINE&NBSP;&NBSP;12 &nbsp;13 &nbsp; #define &NBSP;&NBSP;SOURCE_PORT&NBSP;8000 &nbsp;14&nbsp; &nbsp;15&nbsp; #define &nbsp;&nbsp;source_ip_address &nbsp; "192.168.1.6" &nbsp;16&nbsp; &nbsp;17&nbsp;void&nbsp;process_info (int&nbsp;s) &nbsp;18&nbsp;{&nbsp;19&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;recv_num;
&nbsp;20&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;send_num; &nbsp;21&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;recv_BUF[50];
&nbsp;22&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;char&nbsp;send_buf[50]; &nbsp;23&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while (1) {&nbsp;24&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf ("begin&nbsp;recv:\n"); &nbsp;25&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Recv_num&nbsp;=&nbsp;recv (S,recv_buf,sizeof (RECV_BUF), 0); &nbsp;26&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (recv_num&nbsp;&lt;0) {&nbsp;27&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&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p;printf ("send&nbsp;sucess\n"); &nbsp;41&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } &nbsp;42&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} &nbsp;43&nbsp} &nbsp;44&nbsp;int&nbsp;main () &nbsp;45 &nbsp;{&nbsp;46&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;sock_fd,conn_fd; &nbsp;47&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;client_len;
&nbsp;48&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;pid_t&nbsp;pid; &nbsp;49&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;struct&nbsp;sockaddr_in&nbsp;addr_serv,addr_
Client &nbsp;50&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sock_fd&nbsp;=&nbsp;socket (AF_INET,SOCK_STREAM,0
); &nbsp;51&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (sock_fd&nbsp;&lt;&nbsp;0) {&nbsp;52&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;perror ("Socket
"); &nbsp;53&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Exit (1); &nbsp;54&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{&nbsp;55&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;printf ("sock&nbsp;sucessful\n"); &nbsp;56&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;57&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;//initializes the server-side address &nbsp;58&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;memset (&amp;addr_
Serv,0,sizeof (Addr_serv));
&nbsp;59&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addr_serv.sin_family&nbsp;=&nbsp;AF_INET; &nbsp;60&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addr_serv.sin_port&nbsp;=&nbsp;htons (SOURCE_PORT
); &NBSP;61&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;ADDR_SERV.SIN_ADDR.S_ADDR&NBSP;=INET_ADDR (SOURCE
_ip_address); &nbsp;62&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;client_len&nbsp;=&nbsp;sizeof (struct&nbsp;
SOCKADDR_IN); &nbsp;63&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (Bind (SOCK_FD, struct&nbsp;sockaddr&nbsp;*) &amp;addr_serv,sizeof (Struct&nbsp;sockaddr_in) &lt;0) {&nbsp;64&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbs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p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;printf ("accept&nbsp;a&nbsp;new&nbsp;client,ip:%s\n", Inet_ntoa (ADDR_CLIENT.SIN_ADDR)); &nbsp;83&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;pid&nbsp;=&nbsp;fork (); &nbsp;84&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;if (0&nbsp;==&nbsp;pid) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//subprocess &nbsp;85&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;close (SOCK_FD);//Shut down the server's listening in the child process &nbsp;86&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;process_info (CONN_FD)//Processing information &nbsp;87&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{&nbsp;88&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;close (CONN_FD);//Shut down the client's connection in the parent process &nbsp;89&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;90&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;} &nbsp;91&nbsp; &nbsp;92&nbsp;}





3. Client program:



&nbsp;&nbsp;1&nbsp; #include &lt;stdio.h&gt; &nbsp;&nbsp;2&nbsp; #include &lt;string.h&gt; &nbsp;&nbsp;3&nbsp;# include&lt;stdlib.h&gt; &nbsp;&nbsp;4&nbsp; #include &lt;errno.h&gt; &nbsp;&nbsp;5&nbsp; &nbsp;&nbsp;6&nbsp;# include&lt;sys/types.h&gt; &nbsp;&nbsp;7&nbsp; #include &lt;sys/socket.h&gt; &nbsp;&nbsp;8&nbsp; #include &lt; Unistd.h&gt;//close () &nbsp;&nbsp;9&nbsp; #include &lt;netinet/in.h&gt;//struct&nbsp;sockaddr_in &nbsp;10&nbsp;# Include&lt;arpa/inet.h&gt;//inet_ntoa &nbsp;11&nbsp; &nbsp;12&nbsp; #define &NBSP;DEST_PORT&NBSP;8000 &nbsp;13 &nbsp; #define &nbsp;DEST_IP_ADDRESS&nbsp; "192.168.1.6" &nbsp;14&nbsp; &nbsp;15&nbsp;/* Client processing process * * &nbsp;16&nbsp; Void&nbsp;process_info (int&nbsp;s) &nbsp;17&nbsp;{&nbsp;18&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;int&nbsp;send_num;
&nbsp;19&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;recv_num;
&nbsp;20&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n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nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;exit (1); &nbsp;36&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;else&nbsp;{&nbsp;37&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;recv_buf[recv_num]= ' "; &nbsp;38&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf ("recv&nbsp;sucess:%s\n", recv_buf); &nbsp;39&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &NBSP;40&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} &nbsp;41&nbsp;} &nbsp;42&nbsp;int&nbsp;main (int &nbsp;argc,char&nbsp;*argv[]) &nbsp;43&nbsp;{&nbsp;44&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int &nbsp;sock_fd;
&nbsp;45&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;struct&nbsp;sockaddr_in&nbsp;addr_serv;//Server-side address &nbsp;46&nbsp; &nbsp;47&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sock_fd&nbsp;=&nbsp;socket (AF_INET
, sock_stream,0); &nbsp;48&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (sock_fd&nbsp;&lt;&nbsp;0) {&nbsp;49&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;perror ("sock")
; &nbsp;50&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Exit (1); &nbsp;51&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{&nbsp;52&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf ("sock&nbsp;
Sucessful:\n "); &nbsp;53&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;54&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;memset (&amp;addr_serv,0,sizeof (Addr_serv)); &nbsp;55&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addr_serv.sin_family&nbsp;=&nbsp;af_inet; &nbsp;56&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;addr_serv.sin_port&nbsp;=&nbsp;&nbsp;htons (DEST_
PORT); &NBSP;57&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;ADDR_SERV.SIN_ADDR.S_ADDR&NBSP;=&NBSP;INET_ADDR (
dest_ip_address); &nbsp;58&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (&nbsp;connect) (SOCK_FD, (struct&nbsp;sockaddr&nbsp;*) &amp;addr_serv,sizeof (STRUCT&NBSP;SOCKADDR)) &nbsp;&lt;&nbsp;0) {&nbsp;59&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;perror ("Connect"); &nbsp;60&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
printf ("connect&nbsp; (%d) \ n", errno); &nbsp;61&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Exit (1); &nbsp;62&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{&NBSP;63&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printf ("connect&nbsp;sucessful\n"); &nbsp;64&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;65&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;process_info (SOCK_FD);
&nbsp;66&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;close (SOCK_FD); &nbsp;67&nbsp;}


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.