Linux Socket Programming

Source: Internet
Author: User
Tags sendmsg

Linux socket programming One, socket programming specific function parsing reference URL

Http://www.cnblogs.com/skynet/archive/2010/12/12/1903949.html (This article reproduced in this website, reproduced please indicate the source link)

II. Basics of Socket Programming 2.1 Basic TCP client/server program socket functions

Figure 2.1 TCP Server/client response mode

2.2 TCP three-time handshake

Figure 2.2 TCP three-time handshake establishment connection

2.3 TCP Disconnect

Figure 2.3 TCP four-time handshake disconnection

Third, socket programming details Knowledge Summary 3.1, socket () function
Socket (int domain, int type, int protocol);

The socket function corresponds to the open operation of the normal file. The open operation of a normal file returns a file descriptor, and the socket () is used to create a socket descriptor (socket descriptor), which uniquely identifies a socket. The socket descriptor is the same as the file descriptor, and subsequent operations are useful to it, using it as a parameter to perform some read and write operations.

Just as you can give fopen a different parameter value to open a different file. When creating a socket, you can also specify different parameters to create different socket descriptors, the three parameters of the socket function are:

    • Domain: The Protocol field, also known as the Protocol Family (family). Common protocol families are af_inet, Af_inet6, af_local (or Af_unix,unix domain sockets), Af_route, and so on. The protocol family determines the socket address type, must use the corresponding address in the communication, such as Af_inet decided to use the IPv4 address (32 bits) and the port number (16 bit) combination, Af_unix decided to use an absolute path name as the address.
    • Type: Specifies the socket type. Common socket types are, Sock_stream, Sock_dgram, Sock_raw, Sock_packet, Sock_seqpacket, and so on (what are the types of sockets?). )。
    • Protocol: Therefore, the name of the idea is to specify the agreement. Commonly used protocols are, IPPROTO_TCP, IPPTOTO_UDP, IPPROTO_SCTP, IPPROTO_TIPC, respectively, they correspond to TCP transport protocol, UDP Transmission protocol, STCP transmission protocol, TIPC Transfer Protocol (this agreement will be discussed separately!) )。

Note: Not the above type and protocol can be arbitrarily combined, such as sock_stream can not be combined with IPPROTO_UDP. When protocol is 0 o'clock, the default protocol corresponding to type types is automatically selected.

When we call the socket to create a socket, it returns the socket descriptor that exists in the Protocol family (address family,af_xxx) space, but does not have a specific address. If you want to assign an address to it, you must call the bind () function, or the system will automatically randomly allocate a port when you call Connect (), listen ().

3.2. Bind () function

As mentioned above, the bind () function assigns a specific address in the address family to the socket. For example, the corresponding af_inet, Af_inet6 is to assign a IPv4 or IPv6 address and port number combination to the socket.

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

The three parameters of a function are:

    • SOCKFD: The socket descriptor, which is created through the socket () function and uniquely identifies a socket. The bind () function is to bind a name to the description word.
    • Addr: A const struct SOCKADDR * Pointer that points to the Protocol address to bind to SOCKFD. This address structure differs depending on the address protocol family at which the socket was created, as IPv4 corresponds to:
       struct SOCKADDR_IN {            sa_family_t    sin_family;/* Address family:af_inet */            in_port_t      sin_port;   /* port in Network byte order */            struct in_addr sin_addr;   /* Internet address */       };                 /* Internet address. */        struct IN_ADDR {            uint32_t       s_addr;     /* address in network byte order */};

IPv6 corresponds to:

struct SOCKADDR_IN6 {     sa_family_t     sin6_family;   /* AF_INET6 */     in_port_t       sin6_port;     /* Port number */     uint32_t        sin6_flowinfo;/* IPV6 Flow information */     struct in6_addr sin6_addr;     /* IPV6 Address     *        /uint32_t sin6_scope_id;/* Scope ID (new in 2.4) */};
};
The UNIX domain corresponds to the following:
#define UNIX_PATH_MAX    108 struct Sockaddr_un {     sa_family_t sun_family;               /* Af_unix */     char        Sun_path[unix_path_max];  /* pathname */};
    • Addrlen: Corresponds to the length of the address.

Usually when the server is started to bind a well-known address (such as IP address + port number) to provide services, the client can be used to connect the server, and the client does not specify, there is a system automatically assigned a port number and its own IP address combination. This is why the server usually calls bind () before listen, and the client does not invoke it, but instead generates one randomly from the system at Connect ().

Network byte order and host byte order

host byte-order is what we normally call the big-endian and small-end patterns: Different CPUs have different byte-order types, which are the order in which integers are stored in memory, which is called the host order. The reference standard Big-endian and Little-endian are defined as follows:

A) The Little-endian is the low-bit bytes emitted at the lower address of the memory, high-bit bytes emitted in the memory of the higher address.

b) The Big-endian is the high-bit byte emitted at the low address of the memory, and the low byte is discharged at the upper address of the memory.

network byte order : The 4-byte value is transmitted in the following order: First, 0~7bit, followed by 8~15bit, then 16~23bit, and finally 24~31bit. This transmission order is called the big-endian byte order. because TCP/IP all binary integers in the header are required in this order when they are transmitted over the network, so it is also called the network byte order. the order of bytes, as the name implies, is greater than the order in which the data of a byte type is stored in memory, and a byte of data does not have a sequential problem.

So: When binding an address to a socket, first convert the host byte order into a network byte order, instead of assuming that the host byte order is Big-endian with the network byte order. As a result of this problem has caused a massacre! Because of this problem in the company project code, it leads to a lot of puzzling problems, so remember not to make any assumptions about the host byte-order, so be sure to convert it into a network byte order and assign it to the socket.

3.3, listen (), connect () function

If, as a server, the socket (), bind () is called after the Listen () is invoked to listen to the sockets, the server will receive this request if the client calls connect () to make a connection request.

int listen (int sockfd, int backlog), int connect (int sockfd, const struct SOCKADDR *addr, socklen_t Addrlen);

The first parameter of the Listen function is the socket descriptor to listen to, and the second parameter is the maximum number of connections that the corresponding socket can queue. The socket created by the socket () function defaults to an active type, and the Listen function changes the socket to a passive type, waiting for the client's connection request.

The first parameter of the Connect function is the client's socket descriptor, the second parameter is the server's socket address, and the third parameter is the length of the socket address. The client establishes a connection to the TCP server by calling the Connect function.

3.4. The Accept () function

After the TCP server invokes the socket (), bind (), listen (), it listens for the specified socket address. The TCP client calls the socket (), connect () in turn, and then wants the TCP server to send a connection request. After the TCP server hears this request, it calls the Accept () function to take the receive request, so the connection is established. You can then start network I/O operations, which are similar to read/write I/O operations for normal files.

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

The first parameter of the Accept function is the server's socket descriptor, the second parameter is a pointer to the struct SOCKADDR *, which returns the client's protocol address, and the third parameter is the length of the protocol address. If Accpet succeeds, then its return value is a completely new description Word generated automatically by the kernel, representing the TCP connection to the returned client.

Note: The first parameter of accept is the socket descriptor of the server, which is generated by the server calling the socket () function, which is called the listener socket descriptor, while the Accept function returns the connected socket description Word. A server typically creates only one listener descriptor, which persists throughout the lifetime of the server. The kernel creates a connected socket descriptor for each client connection accepted by the server process, and when the server has completed a service to a customer, the corresponding connected socket descriptor is closed.

3.5, read (), write () and other functions

Everything has only the East wind, the server and the customer has established a good connection. can call network I/O to read and write operations, that is, the implementation of the network of different processes between the communication! Network I/O operations have the following groups:

    • Read ()/write ()
    • Recv ()/send ()
    • Readv ()/writev ()
    • Recvmsg ()/sendmsg ()
    • Recvfrom ()/sendto ()

I recommend using the Recvmsg ()/sendmsg () function, which is the most general I/O function and can actually replace the other functions above. Their declarations are as follows:

#include <unistd.h>ssize_t Read (intFdvoid*buf, size_t count); ssize_t Write (intFdConst void*buf, size_t count); #include<sys/types.h>#include<sys/socket.h>ssize_t Send (intSOCKFD,Const void*buf, size_t Len,intflags); ssize_t recv (intSOCKFD,void*buf, size_t Len,intflags); ssize_t SendTo (intSOCKFD,Const void*buf, size_t Len,intflags,Const structSOCKADDR *dest_addr, socklen_t Addrlen); ssize_t Recvfrom (intSOCKFD,void*buf, size_t Len,intflags,structSOCKADDR *src_addr, socklen_t *Addrlen); ssize_t sendmsg (intSOCKFD,Const structMsghdr *msg,intflags); ssize_t recvmsg (intSOCKFD,structMsghdr *msg,intFlags);

The read function is responsible for reading the content from FD. When read succeeds, read returns the actual number of bytes read, if the returned value is 0 to indicate that the end of the file has been read, and less than 0 indicates an error occurred. If the error is eintr, the read is caused by an interrupt, if econnrest indicates a problem with the network connection.

The Write function writes the nbytes byte content in buf to the file descriptor FD. Returns the number of bytes written when successful. Returns 1 on failure and sets the errno variable. In a network program, there are two possibilities when we write to the socket file descriptor. 1) The return value of write is greater than 0, indicating that some or all of the data is written. 2) The returned value is less than 0, and an error occurs. We are going to deal with the error type. If the error is EINTR, an interrupt error occurred while writing. If the epipe indicates a problem with the network connection (the other party has closed the connection).

Other I do not introduce these several I/O functions, see the Man document or Baidu, Google, the following example will be used to SEND/RECV.

3.6. Close () function

After the server has established a connection with the client, some read and write operations are performed, and the corresponding socket descriptor is closed when the read and write operation is completed, like closing the open file by calling Fclose when the file is opened.

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

Close the default behavior of a TCP socket by marking the socket as closed and then immediately returning to the calling process. The descriptor can no longer be used by the calling process, that is, no longer as the first parameter of read or write.

Note: The close operation simply makes the reference count of the corresponding socket descriptor-1, which triggers the TCP client to send a terminating connection request to the server only if the reference count is 0.

How Network processes Communicate

TheIP address of the network layer uniquely identifies the host in the network, and the Transport layer's protocol + Port uniquely identifies the application (process) in the host. By using triples (IP address, Protocol, port), the process of the network can be identified, and the process communication in the network can use this flag to interact with other processes.

Sockets

① streaming Sockets (Sock--stream): This class of sockets provides connection-oriented, reliable data error-free and repeatable data delivery services . And the data sent is received sequentially . All data that is transmitted using the socket is treated as a continuous byte stream and has no length limitation. This is useful for applications where data stability, correctness, and send/receive sequences are required, and TCP uses that type of interface.

② datagram Sockets (Sock--dgram): Datagram sockets provide services that are non-connected , do not provide correctness checks, and do not guarantee the order in which packets are sent, so that data may be re-sent, lost, etc., and the order of reception is determined by the specific route. However, compared to streaming sockets, the use of datagram sockets has a low network line occupancy rate. In the TCP protocol group, UDP uses the class socket.

③ Original Socket (Sock--raw): This socket is not typically present in the advanced network interface because it is directly accessible to the lower layers of the protocol (such as IP, TCP, UDP, and so on). Used to verify the new protocol implementation or to access new devices that are configured in an existing service, the use of the original socket exists for the compatibility of the application, so the original socket is generally not recommended.

host byte-order is what we normally call the big-endian and small-end patterns: Different CPUs have different byte-order types, which are the order in which integers are stored in memory, which is called the host order.

Linux 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.