c + + Network Programming TCP/IP


Recently, I have more leisure time. When I have time, I will make up my mind to learn cpp. Before that, I had a certain foundation of cpp. So TCP/IP is the background of cpp learning. First write a simple TCP server and client to experience it. What TCP and UDP are so strange and far away when they start to contact network programming.
In fact, we should not separate ourselves from reality and magic ize him. In fact, everything is reasonable and practical. Start with TCP.
When it comes to network programming, we first understand the term socket. Breaking through this term, we have made a big step towards understanding TCP. Let's use a simple analogy to describe what kind of face-to-face communication we do with each other through phone calls or letters. Sockets are our communication tools, telephones or mailboxes. That's all.

The whole process of TCP is similar to that of calling. You need to buy a phone first, then install it, apply for a number and wait for a call.

  • Buy a phone first. socket is the function of installing and buying a phone
 serv_sock = socket(PF_INET, SOCK_STREAM, 0);

When we have a phone, we go to the telephone office to apply for the number

bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr))

After applying for the phone number, there will be a master on site to connect and see if the phone is not available

listen(serv_sock, 5)

I'll just sit at home and wait for my girlfriend's call

accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size)

The process is so simple

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

void error_handling(char *message);

int main(int argc, char const *argv[])
    int serv_sock;
    int clnt_sock;

    struct sockaddr_in serv_addr;
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size;

    char message[] = "Hello World!";

    if (argc != 2)
        printf("Usage : %s <port>\n", argv[0]);

    serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    if (serv_sock == -1)
        error_handling("socket() error");
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(atoi(argv[1]));

    if (bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
        error_handling("bind() error");
    if (listen(serv_sock, 5) == -1)
        error_handling("listen() error");
    clnt_addr_size = sizeof(clnt_addr);
    clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size);
    if (clnt_sock == -1)
        error_handling("accept() error");
    write(clnt_sock, message, sizeof(message));

    return 0;

void error_handling(char *message)
    fputs(message, stderr);
    fputc('\n', stderr);

Keywords: socket network Programming

Added by phpforever on Tue, 12 Nov 2019 19:49:17 +0200