Linux Advanced Programming--10.socket programming

Source: Internet
Author: User

The socket programming under Linux basically includes TCP socket, UDP socket that is raw socket three kinds, where the TCP and UDP socket programming is used to write the application layer of the socket program, we use more, and raw Sockets are used relatively infrequently, not in the scope of this article.

TCP sockets

The general flow of client/server programs based on the TCP protocol is generally as follows:

It can basically be divided into three parts:

first, establish the connection:

    • After the server calls the socket (), bind (), listen () to complete initialization, call accept () block wait, in the state of the listening port
    • After the client invokes the socket () initialization, call Connect () to emit a SYN segment and block waiting for the server to answer
    • The server answers a syn-ack segment, and the client receives it back from connect (), while answering an ACK segment, which the server receives and returns from accept ().

Second, transfer data:

After the connection is established, the TCP protocol provides a full-duplex communication pipeline, and the server side and the client can implement the data transmission through the repeated calls of read and write according to the protocol.

Three, close the connection:

When the data transfer is complete, the server and client can call close to close the connection, one end of the connection is closed, the other end of the Read function will return 0, can be based on this feature to sense the other end of the exit.

Here's a simple echoserver to show you how to create server-side and client code, where the socket-related APIs are highlighted.

Server-side Example:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys /socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define MAXLINE 80#define serv_port 8000int    Main (void) {char buf[maxline];    int LISTENFD = 0;    LISTENFD = socket (af_inet, sock_stream, 0);    sockaddr_in servaddr = {0};    servaddr.sin_family = af_inet;    SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);    Servaddr.sin_port = htons (Serv_port);    Bind (LISTENFD, (SOCKADDR *) &servaddr, sizeof (SERVADDR));    Listen (LISTENFD, 20);    printf ("Accepting connections ... \ n");        while (1) {sockaddr_in cliaddr = {0};        socklen_t Cliaddr_len = sizeof (CLIADDR);        int CONNFD = Accept (LISTENFD, (SOCKADDR *) &cliaddr, &cliaddr_len);        Char Str[inet_addrstrlen];                printf ("Connected from%s at PORT%d\n", Inet_ntop (Af_inet, &cliaddr.sin_addr, str, sizeof (STR)),   Ntohs (Cliaddr.sin_port));     while (true) {int count = read (CONNFD, buf, MAXLINE);            if (count = = 0) break;        Write (CONNFD, buf, Count);        } close (CONNFD);                printf ("Closed from%s at PORT%d\n", Inet_ntop (Af_inet, &cliaddr.sin_addr, str, sizeof (STR)),    Ntohs (Cliaddr.sin_port)); }}

PS: It is important to note that the second parameter of the sock function is Sock_stream, which represents a TCP connection, and later we will introduce a UDP connection by passing in the Sock_dgram.

The server-side principal process is a dead loop that accepts a socket connection and then returns it to the client intact, shutting down the socket after the client exits, and accepting the next socket connection again.

The client code is as follows:

#include <stdio.h>#include <arpa/inet.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#define MAXLINE 80#define SERV_PORT 8000#define MESSAGE "hello world"int main(int argc, char *argv[]){    char buf[MAXLINE];    int sockfd = socket(AF_INET, SOCK_STREAM, 0);    sockaddr_in servaddr = {0};    servaddr.sin_family = AF_INET;    inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);    servaddr.sin_port = htons(SERV_PORT);    if (0 != connect(sockfd, (sockaddr *)&servaddr, sizeof(servaddr)))    {        printf("connected failed");        return 1;    }    write(sockfd, MESSAGE, sizeof(MESSAGE));    int count = read(sockfd, buf, MAXLINE);    printf("Response from server: %s\n",buf);    close(sockfd);    return 0;}
UDP Socket

The typical UDP client/server communication process is as follows:

Because UDP does not need to maintain the connection, the program logic is much simpler, but the UDP protocol is not reliable, there are many mechanisms to ensure the reliability of the communication is implemented in the application layer, may instead need more code.

A typical example is as follows:

/* Server.cpp */#include <stdio.h> #include <string.h> #include <netinet/in.h> #include <arpa/    inet.h> #define MAXLINE 80#define serv_port 8000int Main (void) {char buf[maxline];    Char Str[inet_addrstrlen];    int SOCKFD = socket (af_inet, SOCK_DGRAM, 0);    sockaddr_in servaddr = {0};    servaddr.sin_family = af_inet;    SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);    Servaddr.sin_port = htons (Serv_port);    Bind (SOCKFD, (SOCKADDR *) &servaddr, sizeof (SERVADDR));    printf ("Accepting connections ... \ n");        while (1) {sockaddr_in cliaddr;        socklen_t Cliaddr_len = sizeof (CLIADDR);        int count = Recvfrom (SOCKFD, buf, MAXLINE, 0, (SOCKADDR *) &cliaddr, &cliaddr_len);            if (Count < 0) {printf ("Recvfrom error");        Continue             } printf ("Received from%s at PORT%d\n", Inet_ntop (Af_inet, &cliaddr.sin_addr, str, sizeof (STR)),        Ntohs (Cliaddr.sin_port)); SendtO (sockfd, buf, Count, 0, (SOCKADDR *) &cliaddr, sizeof (CLIADDR)); }}/* client.cpp * * #include <stdio.h> #include <string.h> #include <unistd.h> #include <netinet/ in.h> #include <arpa/inet.h> #define MAXLINE 80#define serv_port 8000int Main (int argc, char *argv[]) {char buf[    MAXLINE];    Char Str[inet_addrstrlen];    int SOCKFD = socket (af_inet, SOCK_DGRAM, 0);    sockaddr_in servaddr = {0};    servaddr.sin_family = af_inet;    Inet_pton (Af_inet, "127.0.0.1", &servaddr.sin_addr);    Servaddr.sin_port = htons (Serv_port); while (Fgets (buf, MAXLINE, stdin)! = NULL) {int count = SendTo (SOCKFD, buf, strlen (BUF), 0, (SOCKADDR *) &se        RVADDR, sizeof (SERVADDR));            if (count = =-1) {printf ("SendTo error");        return 0;        } count = Recvfrom (SOCKFD, buf, MAXLINE, 0, NULL, 0);            if (count = =-1) {printf ("Recvfrom error");        return 0; } write (Stdout_fileno, BUF, Count);    } close (SOCKFD); return 0;}


From for notes (Wiz)

Linux Advanced Programming--10.socket programming

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.