Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Linux C Socket Api?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces "what is Linux C Socket Api" in detail, the content is detailed, the steps are clear, and the details are handled properly. I hope this "what is Linux C Socket Api" article can help you solve your doubts.

High-level programming in UNIX environment describes Socket communication as socket network IPC (inter-process communication), which can be used for communication between computers or within computers. Pipes, message queues, semaphores and shared memory all belong to intra-computer communication.

Socket Api introduces in detail 1. Socket descriptor

The first to arrive is the file descriptor, and I know a little more about Linux's philosophy that everything is a document.

A socket is an abstraction of a communication endpoint. Just as applications use file descriptors, access to sockets requires the use of socket descriptors. Socket descriptors are implemented in UNIX systems using file descriptors.

Include int socket (int domain, int type, int protocal); return value: file (socket) descriptor is returned successfully,-1 is returned if error occurs.

The parameter domain (domain) determines the characteristics of the communication, including the address format. Each domain has its own format to represent the address, indicating that the constant of each domain begins with AF_, which means address family (address family).

The parameter type determines the type of socket and further determines the communication characteristics. The following figure shows some types, but you are free to add support for other types in your implementation.

The parameter protocol is usually 0, which means that the default protocol is selected according to the given domain and socket type. When multiple protocols are supported for the same domain and socket type, you can use the proticol parameter to select a specific protocol. The default protocol for socket type SOCK_STREAM in the A_FINET communication domain is TCP (Transmission Control Protocol), and the default protocol for socket type SOCK_DGRAM in the A_FINET communication domain is UDP (user Datagram Protocol).

A byte stream (SOCK_STREAM) requires a logical connection between a local socket and a remote socket before exchanging data.

Tcp: there are no message boundaries, and it provides byte streaming service. I have written about the unpacking and unpacking of Qt transmission pictures before, and that's the reason.

File descriptors for input and output can be obtained by calling socket and calling the open type. Remember to turn off close when not in use.

two。 Addressing

How to determine a target communication process?

The identification of a process has two parts: the network address of the computer can determine the computer on the network with which it wants to communicate.

The service can determine a specific process on the computer.

2.1 byte order

When communicating between processes on the same computer, there is generally no need to consider byte order.

The TCP/IP protocol stack uses large-end byte order. You can use your own Baidu for byte order.

Linux system is a small-end byte order.

2.2 address format

The address determines the socket endpoints in a particular communication domain, and the address format is related to the specific communication domain. In order to enable addresses of different formats to be passed into socket functions, addresses are strongly translated into a general address structure sockaddr representation.

In Linux, sockaddr_in is defined as follows

Struct sockaddr_in {sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; unsigned char sin_zero [8];}

The member sin_zero is a filled field, which must be set to 0. 0. So the examples found on the Internet are the use of bzero.

The definition of ubuntu that I currently use is as follows:

/ Structure describing an Internet socket address. / struct sockaddr_in {_ SOCKADDRCOMMON (sin); in_port_t sin_port; / Port number. / struct in_addr sin_addr; / Internet address. /

/ * Pad to size of `struct sockaddr'. * / unsigned char sin_ Zero [sizeof (struct sockaddr)-_ _ SOCKADDR_COMMON_SIZE-sizeof (in_port_t)-sizeof (struct in_addr)];}

There are many functions about address query, which will not be listed here.

3. Bind a socket to an address

Use the bind function to bind the address to a socket.

Include int bind (int sockfd, const struct sockaddr * addr, socklen_t len); returned value: 0 for success,-1 for error

It would be nice to use sizeof to calculate the parameter socklen_t.

Some restrictions on the use of addresses:

The port number cannot be less than 1024 unless the process has corresponding privileges (that is, superuser). It can be seen that the rules always vary from person to person, and so are computers.

For Internet domains, socket endpoints can be bound to all system network interfaces if the IP address is specified as ADDR_ANY.

Note: linux's man command can see a detailed description of api, and there are examples, which is pretty good.

4. Establish connection 1 > connect

If you are dealing with a connection-oriented network service (SOCK_STREAM or SOCK_SEQPACKET), you need to establish a connection between the process socket (client) that requests the service and the process socket (server) that provides the service before you start exchanging data. Use connect.

Include int connect (int sockfd, const struct sockaddr * addr, socklen_t len); returned value: 0 for success,-1 for error

Ah, this parameter is so familiar, it is exactly the same as the parameter of the bind function.

When client connects to server, the connection may fail for some reason. You can use the exponential compensation algorithm to solve the problem, you can learn about it.

2 > listen

Server calls listen to declare that connection requests can be accepted:

Include Int listen (int sockfd, int backlog); returned value: 0 for success,-1 for error

The parameter backlog provides a hint to indicate the number of connection requests that the process wants to queue up. The value is determined by the system, but the upper limit is specified by the SOMAXCONN in.

Once the queue is full, the system rejects redundant connection requests.

3 > accept

Once the server calls listen, the socket can receive connection requests. Use the function accept to get the connection request and establish the connection.

Include Int accept (int sockfd, struct sockaddr * restrict addr, socklen_t * restrict len); return value: file (socket) descriptor is returned successfully,-1 is returned if error occurs.

The file descriptor returned by the function accept is a socket descriptor, which is connected to the client calling connect. This new socket descriptor has the same socket type and address family as the original socket (sockfd). The original socket passed to accept is not associated with this connection, but remains available and accepts other connection requests.

If you don't care about the client identity, you can set addr and len to NULL, otherwise addr holds the address of the connected client.

If there is no connection request waiting to be processed, the accept blocks until a request arrives. In addition, server can use poll or select to wait for a request to arrive.

5. Data transmission

Now that the socket endpoint is represented as a file descriptor, you can use read and write to communicate over the socket as long as the connection is established. I hardly use the read and write functions, just learn about them.

1 > sendinclude Int send (int sockfd, const void * buf, size_t nbytes, int flags); returned value: the number of bytes sent is returned successfully, and-1 is returned in error

Note: if the send returns successfully, it does not necessarily mean that the process on the other side of the connection receives the data. What can be guaranteed is that the data has been correctly sent to the network.

The logo I always use is 0.

2 > recvinclude int recv (int sockfd, const void * buf, size_t nbytes, int flags); return value: the length of the message in bytes. If no message is available or the other party has ended in order, 0 is returned. An error returns-1.

It's still zero.

If you want to locate the sender, you can use recvfrom to get the source address of the data sender.

3 > recvfrominclude int recv (int sockfd, void * restrict buf, size_t len, int flag, struct sockaddr * restrict addr, socklen_t * restrict len); return value: the length of the message in bytes. If no message is available or the other party has ended in order, 0 is returned. An error returns-1.

Because the address of the sender can be obtained, recvfrom is usually used for connectionless sockets. Otherwise, recvfrom is equivalent to recv.

After reading this, the article "what is Linux C Socket Api" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report