Linux network programming and socket __arduino

Source: Internet
Author: User
1, Socket overview

Sockets are intended to be sockets, which are used in the network to describe how different programs in a computer communicate with other computer programs.
There are 3 common types of sockets:
1) stream sockets (Sock--stream): The use of a reliable connection-oriented data communication mode, that is, TCP sockets ;
2 Datagram Socket (Raw Sockets): The use of non-connection-oriented data transmission mode, that is, UDP sockets ;
3 Original Socket (SOCK--RAW): No processed IP packets, can be packaged according to the requirements of their own programs. 2. Common Functions

1. Create socket function: Return file descriptor on success, return when failure-1

int socket (int domain,int type,int protocol);
Parameter domain specifies the type of socket (preferably sock_stream,sock_dgram,sock_raw) that is used by the protocol family to create the socket (preferably AF_UNIX,AF_INET,AF_INTE6)
//parameter type.
///parameter protocol is usually set to 0

2. Create link function on specified socket: return 0 on success, return on Failure-1

int connect (int sockfd,const struct sockaddr *serv_addr,socklen_t addrlen);
Parameter SOCKFD is a socket//parameter created by a function socket
serv_addr is an address structure that specifies the server's IP address and port number
//parameter Addrlen as the length of the parameter serv_addr

3. A function that binds a socket to a port: returns 0 on success, or 1 when it fails

int bind (int sockfd,struct sockaddr *my_addr,socklen_t addrlen);
Typically only a server-side program invocation, parameter MY_ADDR specifies the local
//address that SOCKFD will bind to, you can set the parameter my_addr sin_addr to Inaddr_any instead of a certain
// IP addresses can be bound to any network interface.

4, the socket into a passive listener function: Successful return 0, failure to return-1

int listen (int s,int backlog);
The parameter S is a socket, and the parameter backlog specifies the maximum length of the link request queue;

5. Receive connection request function: Return file descriptor on success, return when failure-1

int accept (int s,struct sockaddr *addr,socklen_t *addrlen);
The parameter S is created by a function socket, bound to a local port by a function bind, and then through
//function listen the listener socket
//parameter addr is used to hold the address and port of the host initiating the connection request
// Parameter Addrlen is the size of the struct to which the addr points

6. Send data function on TCP socket: connected

Contains 3 elements: socket s, outgoing data msg, data length len

ssize_t Send (int s,const void *msg,size_t len,int flags);
A function can only be used on a socket that is in a connected state, and the parameter S is a socket description
//character that has already been established, that is, the return value//parameter of the Accept function to the
buffer//parameter Len that holds the data to be sent, the length of the
data to be sent Parameter flags for control options, typically set to 0

7. Receive data function on TCP socket: connected

Contains 3 elements: socket s, receive buffer buf, len length

ssize_t recv (int s,void *buf,size_t len,int flags);
function recv receive//data from the socket descriptor specified in parameter s (must be a connection-oriented socket)
and save to the parameter buf the buffer
//parameter len specified is the buffer length, the parameter flags is the control option, and is generally set to 0

8. Send data function on UCP socket: no connection

ssize_t sendto (int s,const void *msg,size_t len,int flags,const struct sockaddr-*to,socklen_t tolen);
function functions are similar to function send, but function sendto do not require a socket to be connected, so
//This function is usually used to send UDP data, and because it is a connectionless socket, the destination address of the specified data is used when using sendto
//. The parameter msg points to a buffer for data to be sent.
//Parameter len Specifies the length//parameter of the data to
be sent flags is the control option, meaning the same as the same//parameter in the Send function to
specify the destination address, and the length of the destination address is specified by Tolen

9. Receive data function on UDP socket: no connection

ssize_t recvfrom (int s, void *buf,size_t len,int flags,struct sockaddr *from,socklen_t);
Similar to function recv functionality, only function recv can be used for connection-oriented sockets, and function
//recvfrom does not have this restriction, which can be used to receive data
//parameters from connectionless sockets buf point to receive buffers
// Parameter len Specifies the size of the buffer
//parameter flags is the control option, the meaning is consistent with recv
//If the parameter from is Non-null, and the socket is not connection-oriented, then the function recvfrom returns.
The source address//parameter fromlen of the data will be saved in the parameter from Recvfrom the length of the
parameter from before the call to recvfrom the
actual size of the From

10. Turn off socket function:

int close (int fd);
The parameter FD is a socket descriptor;

11, multiplex function:

int select (int n,fd_set *readfds,fd_set *writefds,fd_set *exceptfds,struct timeval *timeout);
Parameter n is the number of file descriptors that need to be monitored
//parameter Readfds Specify a set of readable file descriptors to monitor collection
//Parameters Writefds Specify a collection of writable file descriptors to monitor
Parameter Exceptfds Specifies the collection//parameter timeout of the exception file descriptor that you want to monitor
specify the blocked time
3. Server-side sockets (sockets for receiving connection requests) creation process

Step One: Call the socket function to create the socket.
Step Two: Call the BIND function to assign the IP address and port number.
Part III: Call the Listen function to receive request status.
Fourth Step: Call the Accept function to accept the connection request.

There are also read/write, and close. 4. Client sockets (sockets for sending connection requests) creation process

There are only two steps:
1, call the socket function to create a socket.
2. Call the Connect function to send a connection request to the server side.

There are also read/write, and close. 5, the Linux file Operation

file Descriptor : An integer that the system automatically assigns to a file or socket.

Whenever a file or socket is generated, the operating system automatically returns an integer to us. This integer is the file descriptor, which is the alias of the file or socket that is created, which is convenient to address. File descriptors are also referred to as handles in Windows.

1, open the file:

2, close the file or socket:

3. Write data to file:

4, read the data in the file:

Note: ssize_t = signed int, size_t = unsigned int, are aliases declared by TypeDef for basic data types. Now that you have the basic data type, why do you need to alias it? Because int is currently considered to be 32-bit, and in the past 16-bit OS age, int is 16-bit. depending on the system, the changes in the Times, the basic data types of expression also with the change . If you alias the base data type and change it later, you will only need to modify the TypeDef declaration, which can greatly reduce the code changes. 6. Server-side Instance

A program that accepts a connection request on the server side. Compile and run the program to create the server side that waits for the connection request.

#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, const 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", argv[0]);
    Exit (1);
    //(1) Invoke the socket function to create socket 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)); (2) Call the BIND function to assign the IP address and the port number if (Bind (Serv_sock, (struct sockaddr*) &serv_addr, sizeof (serv_addr)) = = 1) error_
    Handling ("bind () error"); //(3) Call the Listen function to receive the request status if (Listen (Serv_sock, 5) = = 1) error_handling ("Listen () error");
    clnt_addr_size = sizeof (CLNT_ADDR); (4) Call the Accept function to accept the connection request. The call does not return without a connection request until there is a request Clnt_sock = accept (Serv_sock, struct sockaddr*) &clnt_addr, &clnt_
    Addr_size);
    if (Clnt_sock = = 1) error_handling ("Accept () error"); (5) The Write function is used to transmit data.
    Execution to this line indicates that there is already a connection request//The data in the transfer message in a client file with a file descriptor of Clnt_sock (clnt_sock, message, sizeof (message));
Close (clnt_sock);//(6) Close (serv_sock);//(7) return 0;
    } void Error_handling (char *message) {fputs (message, stderr);
    FPUTC (' \ n ', stderr);
Exit (1); }
7, client instance
#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, const 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 (1);
    //(1) Create socket. But this is not immediately divided into client or server-side 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));
        (2) Call the Connect function to send a connection request to the server. This is determined as client if (Connect (sock, (struct sockaddr*) &serv_addr, sizeof (serv_addr)) = = 1)
    Error_handling ("Connect () error"); (3) To call the Read function to save the data in the message array declared by itself 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);//(4) return 0;
    } void Error_handling (char *message) {fputs (message, stderr);
    FPUTC (' \ n ', stderr);
Exit (1); }
7. Basic client/server socket graphic display

Reference: "TCP/IP network Programming" and "UNIX Network programming Volume 1"

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.