C language network programming basics 1.1

Source: Internet
Author: User

After having the basic knowledge of the previous chapter, I think we should start to learn the next step.

I. Socket description

Socket communicates with other programs using UNIX file descriptors (FIEL descriptor. When a UNIX program executes any form of I/O, the program reads or writes a file descriptor. A file descriptor is only an integer associated with the opened file. However (note later), this file may be a network connection, FIFO, pipeline, terminal, file on disk or something else. Everything in UNIXYesFile! Therefore, when you want to communicate with other programs on the internet, you will use the file descriptor. If it is a file descriptor, why not call it normally?Read ()AndWrite ()To communicate through a set of interfaces ?" The simple answer is: "You can use common functions !". The detailed answer is: "You can, but useSend ()AndRecv ()It allows you to better control data transmission ."

2. Two types of Internet interfaces

One is "stream sockets" and the other is "datemedisockets ". We will also use them later"Sock_stream"And"Sock_dgram".

Stream sets are reliable two-way communication data streams. If you output "1, 2" to the security order of the Set interface, they will "1, 2" to the other side. They are also error-free and have their own error control.

The datagram also uses an IP address as the route, but does not select TCP. He uses the "user data protocol (User Data Protocol )".

III,Network TheoryKnowledge

The network layer model can be divided into the application layer (Presentation) Session Layer (Session) Transport Layer (Transport) network layer (Data Link) Physical Layer (physical, in fact, they are like clothes and undresses. When you send a message from your host to other hosts, you start to dress constantly. When the network is transmitted to other hosts, then, we started to get undressed, and the other hosts read the messages you sent. I will not explain it too much here.

Iv. Common network programming structures

The first structure (TM )--Struct sockaddr. This data structure is used to store many types of interfaces. interface address information: struct sockaddr {
Unsigned short sa_family;/* address family, af_xxx */
Char sa_data [14];/* 14 bytes of Protocol address */
};

Sa_familyIt can be a variety of things, but in this article it is"Af_inet".Sa_dataStore the target address and

Port information.

To dealStruct sockaddrThe programmer creates a parallel structure:Struct sockaddr_in("In" stands for "Internet ".)

Struct sockaddr_in {
Short int sin_family;/* address family */
Unsigned short int sin_port;/* Port Number */
Struct in_addr sin_addr;/* Internet address */
Unsigned char sin_zero [8];/* same size as struct sockaddr */
};

This data structure allows you to easily process the basic elements of the Set interface address. Note:Sin_zero(He is added to this structure, and the length andStruct sockaddrSame) function should be usedBzero ()OrMemset ()To set zero for all. Even ifSocket ()What you want isStruct sockaddr *, You can still useStruct sockaddr_inNote:Sin_familyAndStruct sockaddrInSa_familyConsistent and can be set"Af_inet". Finally,Sin_portAndSin_addrIt must be a network byte order ).

You may disagree: "But how to make the entire data structureStruct in_addr sin_addrWhat is the network byte order? "To know the answer to this question, we need to take a closer look at the data structure:Struct in_addr, There is such a union (unions ):

/* Internet address (a structure for historical reasons )*/
Struct in_addr {
Unsigned long s_addr;
};

ItOnceIt's the worst combination, but now those days have passed. If you declare"Ina"Is the data structureStruct sockaddr_inInstance, then"Ina. sin_addr.s_addr"It stores 4 bytes of IP addresses (Network byte order ). If your unfortunate system is still using a horrible combinationStruct in_addrYou can still rest assured that the IP address of the 4-character section is the same as I mentioned above (this is because# Define.)

5. Convert the natives (native conversion)

We began to learn new knowledge. We may have heard that different hosts may store different information in different bytes. In this way, we will also encounter such problems during network transmission, then we need to convert the byte sequence from the network to the local machine to the network. You can convert two types: Short (two bytes) and long (four bytes ). If you want to convert the short from the local bytes to the network byte order, use "H" to indicate the local host ("host"), followed by "", then, use "N" to represent the network ("nerwork"), and then use "S" to represent "short": H-to-n-s or htons (). Of course, I can think of other things as follows:

Htons () -- "host to network short"

Htonl () -- "host to network long"

Ntohs () -- "network to host short"

Ntohl () -- "network to host long"

Now, you may think that you already know them, and you may think that the network byte sequence is already used on your host, and there is no need to use htonl () to convert IP addresses. You are not wrong, but the program will be transplanted to other hosts, it may have a hidden danger. So remember: When you put data on the network, make sure they are in the byte sequence of the network.

Finally, why do sin_addr and sin_port need to be converted to the network byte sequence in the data structure struct sockaddr_in, and does sin_family need it? Sin_addr and sin_port are respectively encapsulated in the packet IP address and UDP layer, so they must be in the byte sequence of the network. However, the sin_family domain is only used by the kernel to determine the type of address contained in the data structure. Therefore, it must be in the local byte sequence. At the same time, sin_family is not sent to the network. They can be local bytes.

6. IP addresses and how to handle them
We are lucky because we have many functions to conveniently operate IP addresses. There is no need to manually calculate them, and there is no need to use the "<" operation to store the growth of the entire font. First, assume that you already have a sockaddr_in struct Ina, and you have an IP address "132.241.5.10" to store it, you need to use the inet_addr () function (), converts an IP address from a point to an unsigned long integer. The usage is as follows:
Ina. sin_addr.s_addr = inet_addr ("132.241.5.10 ");
Note that the address returned by inet_addr () is already in the network byte format, so you do not need to call the function htonl ().
We now find that the code snippet above is not very complete because it does not have an error check. Obviously,-1 is returned when an error occurs in inet_addr. Remember these binary numbers? (Unsigned number)-1 only matches the IP address 255.255.255.255! This is the broadcast address! Very wrong! Remember to perform the error check first.
Now you can convert the IP address to a new integer. Is there an alternative? Can it output an in_addr struct to the point format? In this case, you need to use the function inet_ntoa () ("ntoa" meaning "network to ASCII"), like this: printf ("% s", inet_ntoa (INA. sin_addr ));
It outputs the IP address. Note that inet_ntoa () uses the in-ADDR struct as a parameter rather than a long integer. It also returns a pointer to a character. It is a static and fixed pointer controlled by inet_ntoa (), so every time you call inet_ntoa (), it will overwrite the IP address obtained during the last call. For example:
Char * A1, * A2;
.
.
A1 = inet_ntoa (ina1.sin _ ADDR);/* This is 198.92.129.1 */
A2 = inet_ntoa (ina2.sin _ ADDR);/* This is 132.241.5.10 */
Printf ("address 1: % Sn", A1 );
Printf ("address 2: % Sn", A2 );
The output is as follows:
Address 1: 132.241.5.10
Address 2: 132.241.5.10
If you need to save this IP address, use the strcopy () function to point to your own character pointer.

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.