Anonymous Interface
A set of interfaces does not always need an address. For example, the socketpair function creates two interfaces that are connected to each other, but there is no address. In fact, they are an unknown set of interfaces. Imagine the red phone number between the US president and the Soviet Union during the cold war. They do not need phone numbers at any end, because they are directly connected. Similarly, the socketpair function is directly connected without an address.
Anonymous call
Sometimes, either of the two interfaces in the connection has no address. The remote interface to be connected must be identified by an address. However, the local interface is anonymous. The established connection has an address-less remote interface and another address-less interface.
Generate address
Sometimes we don't mind what our current address is, but we need one for communication. This is usually correct for programs that need to connect to a server (such as an RDBMS data service. Their local addresses are only required for continuous connections. You can also assign a specific address, but this increases network management. Correspondingly, the address is generated only when the address is available.
Understanding domain
When the Berkeley development team is developing BSD interface sets, TCP/IP is still under development. At the same time, some other protocols to be completed are being used by different organizations, such as the X.25 protocol. Other protocols are under study.
The socketpair function we have seen in the previous chapter, and the socket function we will see, it is wise to allow the possibility that other protocols may not be used by TCP/IP. The domain parameter of the socketpair function allows this constraint. For the convenience of the discussion, let's first review the summary of the socketpair function:
# Include <sys/types. h>
# Include <sys/socket. h>
Int socketpair (INT domain, int type, int protocol, int SV [2]);
Generally, the Protocol parameter is set to 0. 0 allows the operating system to select the default protocol used by the selected domain. There are some exceptions to these rules, but this is beyond the scope of our discussion.
Now let's explain the domain parameters. For the socketpair function, the value must be af_local or af_unix. In the previous chapter, we have pointed out that the af_unix macro is equivalent to the af_local macro of the old version. What does af_local mean? What did he choose?
The leading edge of the constant af _ specifies the address family. Select the address family to use for the domain parameter.
Interface address for formatting
Each communication protocol specifies the format of its own network address. Accordingly, the address family is used to specify the type of address to be used. Constant af_local (af_unix) indicates that the address will be formatted according to the local (UNIX) address rules. Constant af_inet indicates that the address will comply with the IP address rules. In an address family, there can be multiple types.
In the following section, we will detect the formats and physical la s of various address families. This is an important part to grasp. Many of the difficulties people encounter when using BSD interfaces are related to address initialization.
Detect common set of interface addresses
Because the BSD interface address is developed earlier than the ansi c standard, there is no (void *) Data Pointer to accept any structure address. The solution for BSD is to define a general address structure. The general address structure is defined using the following C language statement:
# Include <sys/socket. h>
Struct sockaddr {
Sa_family_t sa_family;/* address family */
Char sa_data [14];/* address data .*/
};
Here, the sa_family_t data type is an unsigned short integer, which is two bytes in Linux. The entire structure is 16 bytes. The sa_data [14] of the structure element represents the remaining 14 bytes of the address information.
Displays the physical layout of the general address structure:
The general interface address structure is not that useful for programs. However, he does provide reference models that must be appropriate for other address structures. For example, we will understand that all addresses must define a sa_family member at the same position in the structure, because this element determines the number of remaining bytes of the address structure.
Format local address
This address structure is used in our local socket port (our PC running Linux ). For example, when we use the LPR command to exclude files to be printed, it uses a local interface to communicate with the counterfeit offline server on our PC. Although the TCP/IP protocol can also be used for local communication, it turns out that this is inefficient.
Traditionally, the local address family has been called the af_unix domain. This is because these addresses use local UNIX files as the name of the Set interface.
The address structure of af_local or af_unix is sockaddr_un. This structure is defined by including the following statements in our C program:
# Include <sys/UN. h>
Address structure of sockaddr_un:
Struct sockaddr_un {
Sa_family_t sun_family;/* address family */
Char sun_path [2, 108];/* pathname */
};
The value of the structure member sun_family must be af_local or af_unix. This value indicates that the structure is formatted using the sockaddr_un structure rules.
The structure member sun_path [108] contains an available UNIX path name. This character array does not need to end with NULL bytes.
In the following section, we will learn how to initialize an af_local address and define its length.
Format a traditional local address
The address space of a traditional local address is the path name of the file system. A process may use any available path name to name its local interface. However, in order to be available, the process of the name set interface must be able to access all directory components of the path name, and have the permission to create the final set interface object in the specified directory.
Some programmers prefer to initialize all the addresses to 0 before filling in the address structure. This is usually done through the memset function, and this is a good idea.
Struct sockaddr_un uaddr;
Memset (& uaddr, 0, sizeof uaddr );
This function sets all the bytes of this address structure to 0.
The following example demonstrates a simple C program that initializes the sockaddr_un structure, and then calls the netstat command to prove that it plays a role. Here, we must first remember the program calls on the socket and bind, which are two functions that we have not involved yet.
/*************************************** **
*
* Af_unix.c
*
* Af_unix socket example:
*
**************************************** ***/
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
# Include <errno. h>
# Include <string. h>
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <sys/socket. h>
# Include <sys/UN. h>
/*
* This function reports the error and
* Exits back to the shell:
*/
Static void bail (const char * on_what)
{
Perror (on_what );
Exit (1 );
}
Int main (INT argc, char ** argv, char ** envp)
{
Int Z;/* Status return code */
Int sck_unix;/* socket */
Struct sockaddr_un adr_unix;/* af_unix */
Int len_unix;/* length */
Const char pth_unix [] = "/tmp/my_sock";/* pathname */
/*
* Create a af_unix (aka af_local) socket:
*/
Sck_unix = socket (af_unix, sock_stream, 0 );
If (sck_unix =-1)
Bail ("socket ()");
/*
* Here we remove the pathname for
* Socket, in case it existed from
* Prior run. Ignore errors (it maight
* Not exist ).
*/
Unlink (pth_unix );
/*
* Form an af_unix address:
*/
Memset (& adr_unix, 0, sizeof adr_unix );
Adr_unix.sun_family = af_local;
Strncpy (adr_unix.sun_path, pth_unix,
Sizeof adr_unix.sun_path-1)
[Sizeof adr_unix.sun_path-1] = 0;
Len_unix = sun_len (& adr_unix );
/*
* Now bind the address to the socket:
*/
Z = BIND (sck_unix,
(Struct sockaddr *) & adr_unix,
Len_unix );
If (Z =-1)
Bail ("BIND ()");
/*
* Display all of our bound sockets
*/
System ("netstat-pa -- UNIX 2>/dev/null |"
"Sed-n'/^ active UNIX/,/^ proto/P ;"
"/Af_unix/P '");
/*
* Close and unlink our socket path:
*/
Close (sck_unix );
Unlink (pth_unix );
Return 0;
}
The preceding steps are as follows:
Line 1 defines sck_unix to store the created set interface file descriptor.
2. The local address structure is defined in line 2 and named adr_unix. This program will use an af_local interface address to process this structure.
3. Call the socket function to create a set of interfaces in Row 3. Check and report errors in Row 3.
4. Call the unlink function in line 3. Because the af_unix address will create a file system object and must be deleted if it is no longer needed. If this program is not deleted during the last running, this statement will try to delete it.
5. The address structure of adr_unix on line 5 is cleared by 0.
6. The address family is initialized as af_unix on line 1.
7. Copy the path name "/tmp/my_sock" from rows 57th to 59th to the address structure ". Here we use the code to add a NULL byte to the structure, because the macro sun_len () is provided in line 61st Linux.
8. Calculate the length of the address in the second row. The program here uses the macros provided by Linux. However, this macro is an ending character of the adr_unix.sun_path [] structure member.
9. Call the BIND function in rows 66th to 68 and assign the formatted address to the interface set created in rows 37th.
10. Call the netstat command on line 10 to prove that our address has been bound to a set of interfaces.
11. Close the interface set in line 3.
12 when the BIND function is called, the Unix path name created for the set interface is deleted in row 66th.
In the 61st row, the length is assigned to len_unix. Here the sun_len () macro is used, but it does not calculate the NULL bytes copied to the adr_unix.sun_path [] character array. However, it is necessary to place an empty byte because the sun_len () macro calls the strlen function to calculate the string length of the UNIX path name.
The execution result of the program is as follows:
$./Af_unix
Active Unix domain sockets (servers and established)
PROTO refcnt flags type state I-node PID/program name path
UNIX 0 [] stream 104129 800/af_unix/tmp/my_sock
$
Format Abstract Local Address
One of the troubles of using traditional af_unix interfaces is that they always call file system objects. This is not necessary and inconvenient. If the original file system object is not deleted and the same file name is used in the bind Call, the value assignment fails.
The Linux 2.2 kernel makes it possible to create an abstract name for the Local interface. The method is to make the first byte of the path name an empty byte. The Bytes after the hollow bytes of the path name will become part of the abstract name. The following program is the modified version of the previous subprogram. This program uses some different methods to create an abstract name.
/*************************************** **
* Af_unix2.c
*
* Af_unix socket example
* Create abstract named af_unix/af_local
**************************************** ***/
# Include <stdio. h>
# Include <stdlib. h>
# Include <error. h>
# Include <unistd. h>
# Include <string. h>
# Include <sys/types. h>
# Include <sys/socket. h>
# Include <sys/STAT. h>
# Include <sys/UN. h>
/*
* This function reports the error and
* Exits back to the shell:
*/
Static void bail (const char * on_what)
{
Perror (on_what );
Exit (1 );
}
Int main (INT argc, char ** argv, char ** envp)
{
Int Z;/* Status return code */
Int sck_unix;/* socket */
Struct sockaddr_un adr_unix;/* af_unix */
Int len_unix;/* length */
Const char pth_unix []/* abs. name */
= "Z * My-socket *";
/*
* Create an af_unix (aka af_unix) socket:
*/
Sck_unix = socket (af_unix, sock_stream, 0 );
If (sck_unix =-1)
Bail ("socket ()");
/*
* Form an af_unix address
*/
Memset (& adr_unix, 0, sizeof adr_unix );
Adr_unix.sun_family = af_unix;
Strncpy (adr_unix.sun_path, pth_unix,
Sizeof adr_unix.sun_path-1)
[Sizeof adr_unix.sun_path-1] = 0;
Len_unix = sun_len (& adr_unix );
/*
* Now make first byte null
*/
Adr_unix.sun_path [0] = 0;
Z = BIND (sck_unix, (struct sockaddr *) & adr_unix, len_unix );
If (Z =-1)
Bail ("BIND ()");
/*
* Display all of our bound sockets:
*/
System ("netstat-pa -- UNIX 2>/dev/null |"
"Sed-n'/^ active UNIX/,/^ proto/P ;"
"/Af_unix/P '");
/*
* Close and unlink our socket path:
*/
Close (sck_unix );
Return 0;
/*
* Now bind the address to the socket:
*/
}
The running result of this program is as follows:
$./Af_unix2
Active Unix domain sockets (servers and established)
PROTO refcnt flags type state I-node PID/program name path
UNIX 0 [] stream 104143 5186/af_unix2 @ * My-socket *
$
From this output, we can see that the Set interface address appears in the name of @ * mysocket. The @ sign starts with the netstat command to identify the name of the abstract UNIX interface. The remaining characters are the characters copied to the remaining position of the character array. Note that the @ character appears in the place where our Z character should appear.
The steps of the entire program are the same as those of the previous program. However, the address initialization steps are somewhat different. These steps are described as follows:
1. strings with abstract names of interfaces are defined in rows 31st and 32nd. Note that the first character of the string is Z. The extra character in this string only plays a placeholder role, because it will be replaced by an empty byte in step 2.
2. Call the memset function in row 45th to initialize the entire structure to 0.
3. Set the address family to af_unix in row 47th.
4. Use the strncpy function in row 49th to copy the abstract name to adr_unix.sun_path. Note that an ending NULL byte is placed in the destination character array for the use of the sun_len () Macro. Otherwise, the ending NULL byte is not required.
In 53rd, the length of the address is calculated using the sun_len () C macro provided by Linux. This macro calls the strlen function on sun_path [], so an ending character is required.
6. This step is new: the first byte of the sun_path [] array is set to null. If you use the sun_len () Macro, you must complete this step.
In this section, we learned how to create a set of API addresses for af_local and af_unix. To calculate the length of the Set interface address, we use the sun_len () Macro. However, when calculating the name of an abstract set of interfaces, we should pay attention to it.