Socket communication--linux, using C + +

Source: Internet
Author: User

① What is a socket?

A socket is the endpoint of a communication. A pair of processes in the network directly through a pair of socket communications, one per process.

A socket is determined by an IP address and a port number. Socket encapsulates a number of operations, making the data communication of two processes in the network more convenient. Sockets based on TCP protocol and UDP protocol are used a lot.

Shows the communication process in two ways




② several functions of establishing sockets for communication use

Take the Linux system as an example to illustrate several functions

A Socket () function

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

This action is similar to opening a file operation, which returns the socket descriptor of the socket.

Parameters:

Domain: The Protocol field, also known as the Protocol Family (family). The commonly used protocol families are af_inet, Af_inet6, Af_local, Af_route. The Protocol family determines the address type of the socket, communicates with its corresponding address, af_inet with a combination of IPv4 address (32-bit) and 16-bit port number

Type: Specifies the socket type, commonly used are sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket, the first two sockets corresponding to the TCP and UDP types respectively

Protocol: Specifies the protocol, commonly used with ipproto_tcp, IPPTOTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, protocol and socket types to match. 0 will select the default type corresponding to the types.


B Bind () function

int bind (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);

Assigns specific addresses of an address family to the socket, rather than randomly assigned by the system.

Parameters:

The int value returned by the Sockfd:socket descriptor, socket () function

Addr: A const pointer to an address structure that points to the address to bind to the SOCKFD, the structure of the struct, and the address protocol.

As the IPv4 of the land corresponds

struct SOCKADDR_IN {   sa_family_t    sin_family;/* Address family: af_inet */   in_port_t      sin_port;   /* Port number of the network byte order */   struct in_addr sin_addr;   /*internet address */}; /* Internet address. */struct in_addr {   uint32_t       s_addr;     /* Address of the network byte Order */};

It should be noted that the Htol,htos function is used to convert host byte order to network byte order, avoiding potential errors.

C Listen (), connect () function

Call the socket (), connect (), and then call Listen () to listen for the socket, and the client calls connect, and the server receives the request.

int listen (int sockfd, int backlog);
SOCKFD is the descriptor of the socket to be monitored

The backlog is the maximum number of links that the socket can queue, that is, the length of the waiting queue for the socket. Call Listen,socket to start waiting for a customer's link request

int  Connect (int sockfd, const structsockaddr *addr, socklen_t Addrlen);
SOCKFD is the client socket description Word

Addr The socket address of the server

Addr_len is the length of the socket address.

The client establishes a connection to the TCP server by calling the Connect function. Call Listen (), the socket starts waiting for the customer's link request

D Accept () function

Server-side fourth function to call, after the server receives the request, accept the request with accept, then the link is established, you can start the read and write operation.

int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);

SOCKFD is the server socket description Word

Addr is a pointer to return the client address

Addrlen is the length of the protocol address. The return value of the function is a completely new description word that the kernel automatically generates, representing a TCP link to the client


E.read (), write () read-write operation

The correlation function prototype looks like this

#include <unistd.h>       ssize_t Read (int fd, void *buf, size_t count);      ssize_t Write (int fd, const void *buf, size_t count); #include <sys/types.h> #include <sys/socket.h>       ssize_t Send (int sockfd, const void *buf, size_t len, int f lags);      ssize_t recv (int sockfd, void *buf, size_t len, int flags);       ssize_t sendto (int sockfd, const void *buf, size_t len, int flags,                      const struct SOCKADDR*DEST_ADDR, socklen_t Addrlen) ;      ssize_t recvfrom (int sockfd, void *buf, size_t len, int flags,                        struct SOCKADDR*SRC_ADDR, socklen_t *addrlen);       ssize_t sendmsg (int sockfd, const struct MSGHDR *msg, int flags);       ssize_t recvmsg (int sockfd, struct msghdr*msg, int flags);

E. Close () function

Close the corresponding socket descriptor after reading and writing

#include <unistd.h>int close (int fd);

③ code Example

Code from Http://www.embedu.org/column/column179.htm

TCP sockets

TCP Service Side

int main () {int sock_fd,client_fd;/*SOCK_FD: Listener socket;client_fd: Data transfer socket */struct sockaddr_in ser_addr;/* Native address information */struct sockaddr_in cli_addr; /* Client Address information */char msg[max_msg_size];/* buffer */ser_sockfd=socket (af_inet,sock_stream,0);/* Create a connected socket */if (ser_so                  CKFD&LT;0) {/* Create failed */fprintf (stderr, "Socker error:%s\n", Strerror (errno));          Exit (1);    }/* Initializes the server address */addrlen=sizeof (struct sockaddr_in);    Bzero (&ser_addr,addrlen);    Ser_addr.sin_family=af_inet;    Ser_addr.sin_addr.s_addr=htonl (Inaddr_any);    Ser_addr.sin_port=htons (Server_port); if (bind (SER_SOCKFD, struct sockaddr*) &ser_addr,sizeof (struct sockaddr_in)) {/* bind failed */<0 (fprintf,            "Bind error:%s\n", Strerror (errno));    Exit (1);        }/* Listens for client requests */if (listen (Ser_sockfd,backlog) <0) {fprintf (stderr, "Listen error:%s\n", Strerror (errno));        Close (SER_SOCKFD);    Exit (1); } while (1) {/* Waits to receive client connections pleaseBeg */Cli_sockfd=accept (SER_SOCKFD, (struct sockaddr*) & Cli_addr,&addrlen);        if (cli_sockfd<=0) {fprintf (stderr, "Accept error:%s\n", Strerror (errno));  }else{/* Start Service */recv (cli_addr,msg,max_msg_size,0);/* Accept data */printf ("received a connection from%SN",            Inet_ntoa (CLI_ADDR.SIN_ADDR));            printf ("%s\n", msg);/* print out on the screen */strcpy (msg, "Hi,i am server!"); Send (Cli_addr,msg,sizeof (msg), 0);        /* Data sent */close (CLI_ADDR);    }} close (SER_SOCKFD); return 0; }

TCP Client

int main () {int cli_sockfd;/* client socket */int addrlen;    Char seraddr[14]; The address of the struct sockaddr_in ser_addr,/* server */cli_addr;/* Client address */char msg[max_msg_size];/* buffer */getserveraddr (Seradd    R); Cli_sockfd=socket (af_inet,sock_stream,0);/* Create a connected socket */if (ser_sockfd<0) {/* Create failed */fprintf (stderr, "Socker E        Rror:%s\n ", Strerror (errno));    Exit (1);    }/* Initializes the client address */addrlen=sizeof (struct sockaddr_in);    Bzero (&ser_addr,addrlen);    Cli_addr.sin_family=af_inet;    Cli_addr.sin_addr.s_addr=htonl (Inaddr_any);    cli_addr.sin_port=0; if (Bind (CLI_SOCKFD, (struct sockaddr*) &cli_addr,addrlen) <0) {/* bind failed */fprintf (stderr, "Bind error:%s\n        ", Strerror (errno));    Exit (1);    }/* Initializes the server address */addrlen=sizeof (struct sockaddr_in);    Bzero (&ser_addr,addrlen);    Ser_addr.sin_family=af_inet;    SER_ADDR.SIN_ADDR.S_ADDR=INET_ADDR (SERADDR);    Ser_addr.sin_port=htons (Server_port); if (Connect (cli_sockfd, struct sockaddr*) &amP;ser_addr,&addrlen)/*!=0)/* Request Connection */{/* Connection failed */fprintf (stderr, "Connect error:%s\n", Strerror (errno));        Close (CLI_SOCKFD);    Exit (1);    } strcpy (msg, "Hi,i am client!"); Send (Sockfd,msg,sizeof (msg), 0);/* Sends data */recv (sockfd,msg,max_msg_size,0);    /* Accept Data */printf ("%s\n", msg);/* print out on the screen */close (CLI_SOCKFD); return 0;}

UDP Socket

UDP Service Side

int main () {int ser_sockfd;    int Len;    int Addrlen;    Socklen_t Addrlen;    Char seraddr[100];    struct sockaddr_in ser_addr;    /* Establish socket*/ser_sockfd=socket (af_inet,sock_dgram,0);        if (ser_sockfd<0) {printf ("I cannot socket success\n");     return 1;    }/* Fill in the SOCKADDR_IN structure */addrlen=sizeof (struct sockaddr_in);    Bzero (&ser_addr,addrlen);    Ser_addr.sin_family=af_inet;    Ser_addr.sin_addr.s_addr=htonl (Inaddr_any);    Ser_addr.sin_port=htons (Server_port);        /* BIND client */if (Bind (SER_SOCKFD, (struct sockaddr *) &ser_addr,addrlen) <0) {printf ("connect");    return 1;        } while (1) {bzero (seraddr,sizeof (SERADDR));        Len=recvfrom (Ser_sockfd,seraddr,sizeof (SERADDR), 0, (struct sockaddr*) &ser_addr,&addrlen);        /* Displays the client side's network address */printf ("Receive from%s\n", Inet_ntoa (SER_ADDR.SIN_ADDR));        /* Displays the string sent by the client */printf ("recevce:%s", seraddr); /* Return the string to client side */SendTo (SER_SOCKFD,SERADDR,len,0, (struct sockaddr*) &ser_addr,addrlen); } return 0;}

UDP client

int getserveraddr (char * addrname) {printf ("Please input server addr:");    scanf ("%s", addrname); return 1;}    int main (int argc,char **argv) {int cli_sockfd;    int Len;    Socklen_t Addrlen;    Char seraddr[14];    struct sockaddr_in cli_addr;    Char buffer[256];    GETSERVERADDR (SERADDR);    /* Establish socket*/cli_sockfd=socket (af_inet,sock_dgram,0);        if (cli_sockfd<0) {printf ("I cannot socket success\n");    return 1;    }/* Fill in sockaddr_in*/addrlen=sizeof (struct sockaddr_in);    Bzero (&cli_addr,addrlen);    Cli_addr.sin_family=af_inet;    CLI_ADDR.SIN_ADDR.S_ADDR=INET_ADDR (SERADDR);    Cli_addr.sin_addr.s_addr=htonl (Inaddr_any);    Cli_addr.sin_port=htons (Server_port);    Bzero (buffer,sizeof (buffer));    /* Get the string from the standard input device */Len=read (stdin_fileno,buffer,sizeof (buffer));    /* Send string to server side */sendto (cli_sockfd,buffer,len,0, (struct sockaddr*) &cli_addr,addrlen); /* Receive the server-side returned string */Len=recvfrom (cli_sockfd,buffer,sizeof (buffer), 0, (structsockaddr*) &cli_addr,&addrlen);    printf ("Receive from%s\n", Inet_ntoa (CLI_ADDR.SIN_ADDR));    printf ("Receive:%s", buffer);    Close (CLI_SOCKFD); return 0;}

Description

This article was published by Giantpoplar in CSDN

Article Address http://blog.csdn.net/giantpoplar/article/details/47657303

Reproduced please retain this note

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Socket communication--linux, using C + +

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.