TCP/IP network Programming learning Notes __ Network programming

Source: Internet
Author: User
Tags strcmp in domain htons

Recently learned network programming, made some notes, concise, clear, easy to view themselves, but also hope to let more people see, the general process of network programming is this. 1. The socket creation process that accepts (server) connection requests in Network programming

First step: Call the socket function to create a socket

Step Two: Call the BIND function to assign the IP address and port number

Step three: Call the Listen function to receive request status

Fourth Step: Call the Accept function to accept connection request 2, server-side created sockets are also known as server-side sockets or listening sockets 3, clients only "call the socket function to create sockets" and "call the Connect function to send a connection request to the server side" Two Step 4, file descriptor

Each time a file or socket is generated, the operating system returns an integer assigned to them. This integer will serve as a conduit for good communication between the programmer and the operating system. In fact, a file descriptor is simply a number assigned to a file or socket created by the operating system.

File descriptors are sometimes referred to as file handles, but "handle" is primarily a term in Windows. 5. Agreement

In short, the agreement is to complete the exchange of data and agreed to a good agreement. 6, the creation of sockets

#include <sys/socket.h>

int socket (int domain, int type, int protocol)
    -> returns a file descriptor when successful, returns 1 when failed
protocol clusters used in domain sockets (Protocol Family) information type Socket data Transfer Type Information Protocol protocol information used in communication between computers Protocol Cluster
name Protocol Cluster
Pf_inet IPV4 Internet Protocol Cluster
Pf_inet6 IPV6 Internet Protocol Cluster
Pf_local UNIX protocol cluster for local communication
Pf_packet Protocol clusters for underlying sockets
Pf_ipx IPX Novell Protocol Cluster

The final protocol information that is actually used in the socket is passed through the third parameter of the socket function. Determines the third parameter by the first parameter within the range of the specified protocol cluster. socket Type (type)

The socket type refers to the data transmission mode of the socket, passing through the second parameter of the socket function, which is the only way to determine the data transmission of the socket being created.

Socket Type 1: connection-oriented sockets (Socket_stream)

The characteristics of this method: the data in the transmission process will not disappear data boundary is not present in sequential transmission

In a nutshell, a connection-oriented socket: "Reliable, sequential, byte-based data-oriented sockets for connections"

Socket Type 2: message-oriented sockets (SOCK_DGRAM)

Characteristics of this approach: emphasis on fast transmission rather than transmission sequence data may be lost or corrupted transmitted data have data boundaries limit data size per transmission

Message-oriented sockets have faster transmission speeds than connection-oriented sockets, but cannot avoid data loss or corruption.

"Unreliable, not sequential, socket for high-speed data transmission" Protocol Final selection (third parameter) :, t

Protocol cluster information and socket data transfer methods have been passed through the first two parameters of the socket function, which in general can already create the required sockets. So in most cases you can pass 0 to the third parameter unless you encounter the following:

"There are multiple protocols in the same protocol cluster with the same data transfer mode"

Create the following sockets: "Connection-oriented sockets in the IPV4 protocol cluster", parameter pf_inet refers to IPV4 network protocol clusters, and Sock_stream is a connection-oriented data transmission. The protocols that satisfy these two conditions are only ipproto_tcp, so:

int tcp_socket = socket (pf_inet, sock_stream, ipproto_tcp);

The following sockets are created: "Message-oriented sockets in the IPV4 protocol cluster"

int udp_socket = socket (pf_inet, SOCK_DGRAM, IPPROTO_UDP); 7, address family and data series

IP is the value assigned to a computer to send and receive network data. The port number is not a value assigned to the computer, but a sequence number allocated to the socket to differentiate between sockets created in the program. network addresses (Internet address)

IP addresses fall into two categories: IPv4 and IPv6

Summary: "IP is used to navigate to a specific host, and the port number is used to navigate to a specific program on a host." ”

The port number does not allow duplicates, but the TCP sockets and UDP sockets do not have a common port number, so duplicates are allowed. For example, if a TCP socket uses port No. 9190, the other TCP sockets cannot use 9190, but the UDP sockets can be used.

In short, the data transfer destination address contains both the IP address and the port number, which is the only way to transmit the information to the final application. Representation of address information

The IP address and port number used in the application are defined in the form of a struct

struct sockaddr_in
{
    sa_family_t     sin_family;     Address family (addressing Family)
    uint16_t        sin_port;       16-bit TCP/UDP port number
    struct in_addr  sin_addr;       32-bit IP address
    char            sin_zero[8];    Do not use
}

Another structure mentioned in this structure, IN_ADDR, is defined as the following, which is used to store 32-bit IP addresses

struct in_addr
{
    in_addr_t       s_addr;         32-bit IPv4 address
}

The network byte order is the same as the big-endian sequence

Server-side common socket initialization process

int serv_sock;
struct sockaddr_in serv_addr;
Char *serv_port = "9190";

Create a server-side socket (listening socket)
serv_sock=socket (pf_inet,sock_stream,0);

Address information initialization
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 (SERV_ADDR));

Assign address information
bind (Serv_sock, (struct sockaddr*) &serv_addr, sizeof (SERV_ADDR));
8. Server-side and client based on TCP

According to the different data transmission mode, the socket based on network protocol is generally divided into TCP socket and UDP socket. Because TCP sockets are connection-oriented, they are also called sockets based on stream (stream).

Server-side waiting for connection request state is when a client requests a connection, the request connection is pending until the connection is accepted.

Hello World server-side code, HELLO_SERVER.C

int main (int argc, char *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", agrv[0]);
    Exit (1);
    } 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);
    Close (Clnt_sock);
    Close (Serv_sock);
return 0;
    } void Error_handling (char *message) {fputs (message, stderr);
    FPUTC (' \ n ', stderr);
Exit (1); }

Hello World Client, HELLO_WORLD.C

int main (int argc, char *argv[]) {int sock;
    struct sockaddr_in serv_addr;
    Char message[30];

    int str_len;
        if (argc!= 3) {printf ("Usage:%s <IP> <port>\n", argv[0]);
    Exit (0);
    } sock = socket (pf_inet, sock_stream, 0);
    if (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=INET_ADDR (argv[1]);

    Serv_addr.sin_port=htons (Atoi (argv[2));

    if (Connect (sock, (struct sockaddr*) &serv_addr, sizeof (SERV_ADDR)) ==-1) error_handling ("Connect () error");
    Str_len = Read (sock. message, sizeof (message)-1);
    if (Str_len = = 1) {error_handling ("read () error");
    printf ("Message from server:%s\n", message);
    Close (sock);
return 0;
    } void Error_handling (char *message) {fputs (message, stderr);
    FPUTC (' \ n ', stderr);
Exit (1); }
9. Server-side/client based on UDP features of UDP sockets

The letter explains how UDP works, and it exactly matches the UDP feature. Before sending a letter, you should fill in the address of the sender and the addressee on the envelope, then put the stamp in the mailbox. Of course, the character of the letter makes it impossible to confirm the receipt. In addition, there may be a loss of correspondence during the mailing process. In other words, letters are an unreliable form of transmission. Similarly, UDP provides the same unreliable data transfer services.

Flow control is the most important symbol for distinguishing between UDP and TCP. The life of TCP lies in flow control. TCP has flow control in an unreliable IP layer, and UDP has no such flow control mechanism.

The most important function of UDP is to pay to the final UDP socket the packets that are uploaded to the host based on the port number.

The reason TCP is slower than UDP usually has the following two points: connection settings before and after sending and receiving data and the flow control added to ensure reliability in the process of sending and receiving data the server and client are not connected in UDP based server/client UDP

The UDP server-side/client does not exchange data in a connected state, as TCP does, and therefore does not require a connection process, unlike TCP. That is, you do not have to invoke the Listen function and the Accept function that are called during the TCP connection. Only sockets and data exchange procedures are created in UDP. UDP server-side and client only need 1 sockets

In TCP, a one-to-one relationship should be between sockets. To provide services to 10 clients, you need 10 server-side sockets in addition to the gatekeeper server sockets. In UDP, however, only 1 sockets are required for both the server side and the client. UDP-based data I/O functions

After you create a TCP socket, you do not need to add address information when you transfer data. Because the TCP socket will remain connected to the other socket. In other words, the TCP socket knows the destination address information. However, the UDP socket will not remain connected (the UDP socket has only a simple mailbox feature), so the destination address information is added each time the data is transmitted. This is the equivalent of adding an address to a letter before sending it.

UDP-related functions called when data is transferred

#include <sys/socket.h>

ssize_t sendto (int sock, void *buff, size_t nbytes, int flags, struct sockaddr *to, Sockl En_t Addrlen);

    Returns the number of bytes transmitted when the-> succeeds, or returns 1

    sock the    UDP socket file descriptor used to transmit data buff the    buffer address value to hold the data to be transferred
    nbytes  The length of the data to be transmitted, The flags in bytes
    are   optional arguments, and if not, the address value of the SOCKADDR struct variable that passes 0 to hold the      destination address information
    Addrlen The address value structure variables passed to the parameter to the length of the structural body variable

Functions that receive UDP data

#include <sys/socket.h>

ssize_t recvfrom (int sock, void *buff, size_t nbytes, int flags, struct sockaddr, *from, Socklen_t *addrlen);

    Returns the number of bytes received when the-> succeeds, and returns 1 when it fails

The most central part of writing a UDP program is the above two functions. Echo Server-side/client based on UDP

Unlike UDP and TCP, there is no request-and-accept process, so there is no way to distinguish between servers and clients in a sense, simply because they provide services and are called server-side.

Uecho_server.c

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <

arpa/inet.h> #include <sys/socket.h> #define buf_size void error_handing (char *message);
    int main (int argc, char *argv) {int serv_sock;
    Char Message[buf_size];
    int str_len;
    Socklen_t CLNT_ADR_SZ;
    struct sockaddr_in Serv_adr,clnt_adr;
        if (argc!= 2) {printf ("Usage:%s <port>\n", argv[0]);
    Exit (1);
    } Serv_sock = socket (pf_inet,sock_dgram, 0);

    if (Serv_sock = = 1) error_handling ("UDP Socket Creation error");
    memset (&serv_adr, 0, sizeof (SERV_ADR));
    Serv_adr.sin_family=af_inet;
    Serv_adr.sin_addr.s_addr=htonl (Inaddr_any);

    Serv_adr.sin_port=htons (Atoi (argv[1));

    if (Bind (Serv_sock,, (struct sockaddr*) &serv) _adr, sizeof (SERV_ADDR)) ==-1) error_handling ("Bind () error");
        while (1) {clnt_adr_sz=sizeof (CLNT_ADR); Str_len=recvfrom (serv_sock, message, BUF_size, 0, (struct sockaddr*) &clnt_adr, &AMP;CLNT_ADR_SZ);
    SendTo (serv_sock, message, Str_len, 0, (struct sockaddr*) &clnt_adr, CLNT_ADR_SZ);
    Close (Serv_sock);
return 0;
    } void Error_handling (char *message) {fputs (message, stderr);
    FPUTC (' \ n ', stderr);
Exit (1); }

Uecho_client.c does not exist for connect function calls

#include < "same as UECHO_SERVER.C" > #define buf_size void error_handling (char *message);
    int main (int argc, char *argv[]) {int sock;
    Char Message[buf_size];
    int str_len;

    Socklen_t ADR_SZ;
    struct sockaddr_in serv_adr, Clnt_adr;
        if (argc!= 3) {printf ("Usage:%s <IP> <port>\n", argv[0]);
    Exit (1);
    } sock = socket (pf_inet, SOCK_DGRAM, 0);
    if (sock ==-1) {error_handling ("socket () error");
    } memset (&serv_adr, 0, sizeof (SERV_ADR));
    Serv_adr.sin_family=af_inet;
    SERV_ADR.SIN_ADDR.S_ADDR=INET_ADDR (argv[1]);

    Serv_addr.sin_port=atoi (argv[2]));
        while (1) {fputs ("Inert message (Q to quit):", stdout);
        Fgets (message, sizeof (message), stdin);

        if (!strcmp, "q\n") | | |!strcmp (message, "q\n");
        SendTo (sock, message, strlen (message), 0, (struct sockadr*) &serv_adr, sizeof (SERV_ADR));
        Adr_sz=sizeof (FROM_ADR); Str_len=recvfrom (SocK, message, Buf_size, 0, (struct sockaddr*) &from_adr, &AMP;ADR_SZ);
        message[str_len]=0;
    printf ("Message from server:%s", message);
    Close (sock);
    return 0} void error_handling (char *message) {fputs (message, stderr);
    FPUTC (' \ n ', stderr);
Exit (1); }

TCP automatically assigns IP addresses and port numbers when the Connect function is invoked, and UDP automatically assigns IP and port numbers when the SendTo function is invoked.

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.