C Language-socket Communication

Source: Internet
Author: User
Tags ack rfc

Turn from: http://blog.sina.com.cn/s/blog_48d101870100n7e9.html

Directory: 1 What is a socket.
2 The two types of Internet sockets
3) Network theory
4) Structural body
5) Native Conversion
6 IP address and how to deal with them
7) socket () function
8) bind () function
9 Connect () function
) Listen () function
One) accept () function
Send () and recv () function
SendTo () and recvfrom () functions
The close () and shutdown () functions
) Getpeername () function
GetHostName () function
17 Domain Name Service (DNS)
18 client-Server background knowledge
19 Simple Server
20 Simple Client
21) Datagram Socket socket
22) Blocking
Select ()--Multiple sync I/O
24) reference materials
--------------------------------------------------------------------------------
What is a socket.
You often hear people talking about "sockets," and maybe you don't know exactly what it means. Now let me tell you: It's a way to communicate using the standard UNIX file descriptor (descriptor) and other programs. What the. You may have heard some Unix hacker say, "Yes, everything in Unix is a file." "That guy may be talking about the fact that a Unix program is reading or writing a file descriptor when executing any form of I/O." A file descriptor is just an integer associated with an open file. But (note the latter), this file may be a network connection, FIFO, pipe, terminal, file on disk or something else. All the things in Unix are files. So, when you want to communicate with other programs on the Internet, you're going to use a file descriptor. You must understand what you just said. Now you may have this idea in your head: "Where do I get the file descriptor for network communications?" "I will answer this question anyway: you use the system to call the socket (), it returns the socket descriptor (socket descriptor), and then you go through it for Send () and recv () calls. "But ...", you may have a lot of doubt, "if it is a file descriptor, then why not use the general call read () and write () for socket communication. "The simple answer is:" You can use it. ”。 The detailed answer is: "You can, but using Send () and recv () allows you to better control the data transfer." "There is such a situation: there are many kinds of sockets in our world." There are DARPA Internet addresses (Internet sockets), local node path names (Unix sockets), CCITT X.25 addresses (you can completely ignore X.25 sockets). Maybe there's something else on your UNIX machine. We only talk about the first type here: Internet sockets.
--------------------------------------------------------------------------------
Two types of Internet sockets
What do you mean. There are two types of Internet sockets. Yes. No, I'm lying. There's a lot more, but I don't want to scare you. We only talk about two kinds here. In addition to these, I intend to introduce another "Raw Sockets" is also very powerful, it is worth checking.
So what are the two types of these? One is "stream Sockets" (streaming format) and the other is "Datagram Sockets" (packet format). We will also use "Sock_stream" and "Sock_dgram" when we talk about them in the future. Datagram sockets are sometimes called "connectionless sockets" (Connect () If you really want to connect. The streaming socket is a reliable two-way traffic data stream. If you output "1,2" sequentially to sockets, they will "1,2" to the other side in order. They are passed without error, with their own error control, not discussed here.
What's in the use of streaming sockets. You've probably heard of Telnet, haven't you? It uses streaming sockets. You need the characters you have entered in order to arrive, aren't you. Similarly, the HTTP protocol used by WWW browsers uses them to download pages. In fact, when you telnet to a WWW site via port, and then enter "Get PageName", you can also obtain HTML content. Why streaming sockets can achieve high quality data transfer. This is because it uses "Transmission Control Protocol (the Transmission Control Protocol)", also known as "TCP" (please refer to RFC-793 for more information.) TCP controls that your data arrives in order and is not wrong
Miss. You may have heard "TCP" because you heard "TCP/IP." IP here refers to "Internet protocol" (refer to RFC-791.) IP only deals with Internet routing.
So what about the datagram socket? Why is it called connectionless? Why it is unreliable. There are some facts: if you send a datagram, it may arrive, and it may be reversed in order. If it arrives, then there is no error in the inside of the package. Datagrams also use IP for routing, but it does not use TCP. It uses the Subscriber Datagram Protocol (user Datagram Protocol), also known as "UDP" (refer to RFC-768.) )
Why are they not connected? This is mainly because it does not maintain a connection like a streaming socket. You just create a package, construct an IP header with the target information, and then send it out. No connection required. They are usually used to transfer packet-packet information. Simple apps are: TFTP, BOOTP, and so on.
You might think, "if the data is missing, how the program works." "My friend, each program has its own protocol on UDP." For example, each of the TFTP protocols sent to a packet, the recipient must send back a package to say "I received it." "(a command correct answer is also called" ACK "package). If the sender does not receive an answer for a certain amount of time (for example, 5 seconds), it will resend until an ACK is received. This ACK process is important when implementing a SOCK_DGRAM application.
--------------------------------------------------------------------------------
Network theory
Now that I've mentioned the protocol layer, it's time to discuss how the Web works and some examples of how the Sock_dgram package is built. Of course, you can also skip this paragraph if you think you already know it.
Now is the time to learn about data encapsulation (encapsulation). It's very, very important. It is important to you in the web-based curriculum (Figure 1: Data encapsulation) In practice, you have to master it anyway. The main content is: A package, first by a protocol (here is TFTP) in its header (perhaps the tail) packaging ("encapsulation"), the entire data (including the TFTP header) is then encapsulated by another protocol (here is UDP), and then the next (IP) is repeated until the hardware (physical) Layer (this is Ethernet).
When another machine received the packet, the hardware stripped the Ethernet head first, the kernel stripped IP and UDP head, TFTP program and then stripped TFTP head, the final data. Now we're finally talking about the infamous network layering model (layered network models). This network model has many advantages over other models in describing network systems. For example, you can write a socket program without having to care about the physical transmission of the data (serial port, Ethernet, Connection Unit Interface (AUI) or other media), because the underlying program will handle them for you. The actual network hardware and topology are transparent to programmers.
No more nonsense, I now list the entire hierarchy model. If you want to take an online exam, be sure to remember:
Application Layer (application)
Presentation Layer (presentation)
Conversation Layer (session)
Transport Layer (transport)
Network Layer (Network)
Data Link Layer
Physical Layer (physical)
The physical layer is hardware (serial port, Ethernet, etc.). The application layer is the furthest away from the hardware layer-it is where users and networks interact.
This model is so generic that if you want to, you can use it as a car repair guide. It corresponds to Unix, and the result is:
Application layer (Application Layer) (telnet, FTP, etc.)
Transport Layer (Host-to-host transport Layer) (TCP, UDP)
Internet layer (Internet Layer) (IP and routing)
Network access Layer (Network access Layer) (Network layer, data link layer and physical layer)
Now, you may see how these layers are coordinated to encapsulate the original data.
See how much work is done to build a simple packet. Gee, you're going to have to use "cat" to build the packet header. It's just a joke. What you want to do with the streaming socket is send () sending the data. For datagram sockets, you encapsulate the data in the way you choose and then use SendTo (). The kernel will create a transport layer and an Internet layer for you, and the hardware completes the network access layer. This is modern technology.
Now end our crash course in Network theory. Oh, I forgot to tell you about the routing thing. But I'm not going to talk about it, if you really care, then refer to IP RFC.
--------------------------------------------------------------------------------
Structural body
Finally talked about programming. In this chapter, I will talk about the various data types used by the quilt. Because some of their content is important.
The first is a simple one: the socket descriptor. It is the following type:
Int
is just a common int.
From now on, things are going to be amazing, and all you need to do is keep watching. Note the fact that there are two byte permutations: the important byte (sometimes called "octet", or the eight-bit group) in front, or the unimportant byte in front. The former is called "Network byte order (network byte)." Some machines store data in this order internally, while others do not. When I say that a data must be in Nbo order, you call a function (such as htons ()) to convert it from native byte order (Host byte). If I don't mention Nbo, then let it keep native byte order.
My first structure (in this technical manual tm)--struct sockaddr. This structure stores socket address information for many types of sockets:
struct SOCKADDR {
unsigned short sa_family;
Char sa_data[14];
};
Sa_family can be a variety of types, but in this article all are "af_inet". Sa_data contains the destination address and port information in the socket. This seems to be a bit unwise.
To deal with struct sockaddr, programmers create a parallel structure: struct sockaddr_in ("in" means "the Internet"). )
struct SOCKADDR_IN {
short int sin_family;
unsigned short int sin_port;
struct IN_ADDR sin_addr;
unsigned char sin_zero[8];
};
This data structure makes it easy to handle the basic elements of a socket address. Note that Sin_zero (which is added to this structure, and the same length as struct sockaddr) should use the function bzero () or memset () to zero all. At the same time, this important byte, a pointer to the SOCKADDR_IN structure, can also be directed to the struct sockaddr and replace it. In this case, even if the socket () wants a struct sockaddr *, you can still use struct sockaddr_in and convert it at the end. Also, note that the sa_family in sin_family and struct sockaddr are consistent and can be set to "Af_inet". Finally, the Sin_port and sin_addr must be network byte order (network byte orders).
You might disagree: "But how do you get the entire data structure struct IN_ADDR sin_addr in network byte order?" to know the answer to this question, we need to take a closer look at this data structure: struct IN_ADDR, there is such a union (unions) :

struct IN_ADDR {
unsigned long s_addr;
};

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.