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

How to use Socket programming to move from IPv4 to IPv6 support

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article introduces you how to use Socket programming from IPv4 to IPv6 support, the content is very detailed, interested friends can refer to, hope to help you.

At present, in the mainstream IT system, one of the main solutions to solve the communication between internal modules and different systems in distributed systems is to use socket Socket to develop applications. Since most of the current running IT systems use socket Socket development environment is basically based on IPv4, so in the IT system from IPv4 to IPv6 evolution plan, how to complete the evolution of these related applications is particularly critical.

1. Interface Protocol based on SOCKET Technology

BSD Socket API (Win Socket API for Windows platform) is usually used as the basic development application protocol. The following interface protocols are commonly used in IT systems:

Interface protocols based on SOCKET technology usually develop application protocols based on SOKET API. The following table shows the interface protocols commonly used in IT systems:

Serial number protocol name type

1 TELNET TCP

2 SSH TCP

3 FTP TCP

4 TFTP TCP

5 SNMP UDP

6 SOCKET custom TCP/UDP,IT system or vendor's private protocol based on SOKET API definition

Telnet protocol is a member of TCP/IP protocol family, and it is the standard protocol of Internet remote login service. The application of Telnet protocol can turn the computer used by local users into a terminal of the remote host system. It provides three basic services:

(1) Telnet defines a network virtual terminal to provide a standard interface for remote systems. Client programs do not need to know about remote systems in detail, they just need to construct programs that use standard interfaces

(2) Telnet includes a mechanism that allows clients and servers to negotiate options, and it also provides a set of standard options;.

(3) Telnet symmetrically handles both ends of the connection, that is, Telnet does not force the client to enter from the keyboard, nor does it force the client to display output on the screen.

The English full name of SSH is Secure Shell. By using SSH, you can encrypt all transmitted data, making man-in-the-middle attacks impossible and preventing DNS and IP spoofing. An additional benefit is that the transmitted data is compressed, so the speed of transmission can be accelerated. SSH has many functions. It can not only replace telnet, but also provide a secure "channel" for ftp, pop, and even ppp.

From the client side, SSH provides two levels of security authentication: the first level (password-based security authentication) as long as you know your account number and password, you can log in to the remote host. All transmitted data will be encrypted, but there is no guarantee that the server you are connecting to is the server you want to connect to. There may be other servers pretending to be real servers, that is, being attacked by "middlemen". The second level (key-based security authentication) relies on keys, that is, you must create a pair of keys for yourself and place the public keys on the server you need to access. If you want to connect to the SSH server, the client software will send a request to the server for security authentication with your key. After the server receives the request, you look for your public key in the server's HOME directory, and then compare it with the public key you sent. If the two keys match, the server encrypts the "challenge" with the public key and sends it to the client software. After receiving the "CHAP", the client software can decrypt it with your private key and send it to the server. In this way, you must know the password of your key. However, compared with the first level, the second level does not need to transmit passwords on the network. The second level not only encrypts all transmitted data, but also the "man in the middle" attack is impossible (because he doesn't have your private key).

FTP is one of the protocols in the TCP/IP protocol group, it works on the application layer of the TCP model, using TCP transmission, FTP needs two ports, one port is used as a control connection port, that is, port 21, used to send instructions to the server side and wait for the server side response; the other port is the data transmission port, port number 20 (PORT mode only), is used to establish data transmission channel.

The full name of TFTP is Trivial File Transfer Protocol, and the Chinese name is simple File transfer Protocol. As you can see from its name, it is suitable for transferring "simple" files. Unlike FTP, it uses port 69 of UDP, so it can traverse many firewalls. However, it also has some disadvantages, such as unreliable transmission, no password authentication and so on. Even so, it is very suitable for transferring small files.

The predecessor of SNMP (Simple Network Management Protocol, simple Network Management Protocol) is simple Gateway Monitoring Protocol (SGMP), which is used to manage communication lines. Subsequently, people made a lot of changes to SGMP, especially the addition of Internet

< http://baike.baidu.com/view/11165.htm>

Defined SMI and MIB: architecture, and the improved protocol is known as SNMP. The goal of SNMP is to manage the software and hardware platforms produced by many manufacturers on the Internet Internet, so SNMP is also greatly influenced by the Internet standard network management framework. Now SNMP has come out to the third version of the protocol, and its function has been greatly enhanced and improved than before.

The architecture of SNMP is designed around the following four concepts and objectives: to keep the software cost of the management agent (Agent) as low as possible; to maximize the function of remote management in order to make full use of the network resources of Internet; the architecture must have room for expansion; to maintain the independence of SNMP, independent of specific computers, gateways and network transport protocols.

2. Differences of SOCKET API APIs:

The applications based on socket Socket API basically use the same programming model, and all the basic operations of communication, such as connect, accept, listen, send/sendto, read/readfrom and so on, are completed through the Socket API function. This is basically the same no matter in the network environment of IPv4 or in the network environment of IPv6, which ensures that the software structure of the application software developed based on socket Socket is basically unchanged, and the changes brought about by the evolution from IPv4 to IPv6 are mainly concentrated in those address-related API functions (including address-related data structures). RFC2553 has a clear definition of the changes in the socket Socket API function brought about by IPv6. The difference between IPv4 and IPv6 in the socket Socket API function level can be expressed in the following table:

Mapping item function description IPv4 IPv6

Constant defines the address family AF_INET AF_INET6

Protocol family PF_INET PF_INET6

IP address structure sockaddr_in sockaddr_in6

Structure member: socket length sin_len sin6_len

Structure member: protocol family sin_family sin6_family

Structure member: Port number sin_port sin6_port

Address wildcard address INADDR_ANY in6addr_any

Loopback address INADDR_LOOPBACK in6addr_loopback

Address-expression conversion function string address is converted to IP address inet_aton () inet_pton ()

The IP address structure is converted to the string inet_ntoa () inet_ntop ()

The name-address translation function obtains the IP address gethostbyname () getaddrinfo () based on the name

Get the name gethostbyaddr () getnameinfo () based on the IP address

Get the IP address gethostbyname2 () getaddrinfo () according to the name

Get all the service information according to the service name getservbyname () getaddrinfo ()

Get all the service information according to the service port getservbyport () getaddrinfo ()

Those applications developed in languages such as C _ API + basically focus on these changes in the functions and structures of the Web.

JAVA as the main programming language:

Java is a programming language widely used in IT systems at present. The complete class definition of socket Socket programming is provided in the java.net package of JDK (including javax.net package). Applications developed in Java language are based on these classes. JDK has partially supported the IPv6 protocol since version 1.4, and fully supported the IPv6 protocol stack when it comes to JDK1.5 and JDK1.6. The results of the current network survey show that most IT systems can be run in JDK1.5 or above. So we can assume that the JDK we use today already has the capability of IPv6. There are only two classes related to IPv4 and IPv6 in JDK: java.net.Inet4Address and java.net.Inet6Address, that is, if you want to distinguish between IPv4 and IPv6, you can distinguish between the two classes, and both classes inherit from the same parent class java.net.InetAddress. In JDK, all other classes related to the socket Socket are only related to this parent class java.net.InetAddress. It is not directly related to IPv4 (java.net.Inet4Address) and IPv6 (java.net.Inet6Address), that is, whether these classes are transparent to IPv4 or IPv6, so there is no difference in terms of socket Socket API interface.

3. The main technologies involved in software refactoring

Through the above analysis, we know the differences in the socket Socket API interface brought about by the evolution from IPv4 to IPv6. On the basis of understanding and paying attention to these differences, we help us reconstruct the software code to achieve the evolution to IPv6 through the analysis of some key technical points.

In the Socket software developed by using the CumberCraft + language, we mainly focus on the following technical key points:

3.1 changes in address structure

In IPv4 environment, the commonly used address structure sockaddr_in is defined in the header file as follows:

Struct sockaddr_in {

Short int sin_family

Unsigned short int sin_port

Struct in_addr sin_addr

Unsigned char sin_zero [8]

}

Struct in_addr {

Unsigned long s_addr

}

In socket programming for IPv4 programming, the assignment example for the above address structure is as follows:

Rcv_udp_addr.sin_family = AF_INET

Rcv_udp_addr.sin_addr.s_addr = htonl (INADDR_ANY)

Rcv_udp_addr.sin_port = htons (UDPRCV_PORT)

In IPv6 environment, the corresponding changes in address structure are defined as follows:

Struct sockaddr_in6 {

Uint8_t sin6_len

Sa_family_t sin6_family

In_port_t sin6_port

Uint32_t sin6_flowinfo;

Struct in6_addr sin6_addr;

Uint32_t sin6_scope_id

}

Struct in6_addr {

Uint8_t s6_addr [16]

}

The relative assignment to the IPv6 address structure is as follows:

Rcv_udp_addr.sin6_family = PF_INET

Rcv_udp_addr.sin6_addr.s6_addr = in6addr_any

Rcv_udp_addr.sin6_prot = htons (UDPRCV_PORT)

It should be noted that the address in the address structure in IPv4 sin_addr is the host byte order (converted by the htons () function)

In IPv6, the network byte order is used directly.

3.2 creation of socket

The API function definition prototype for establishing a connection to socket is as follows:

Int socket (int domain,int type,int protocol)

For IPv4, domain=AF_INET, and IPv6, domain=PF_INET6

For example, the Socket statement to create a TCP is as follows:

Sock_tcp_ipv4 = socket (AF_INET,SOCK_STREAM,0)

Sock_tcp_ipv6 = socket (PF_INET6,SOCK_STREAM,0)

3.3.Mutual translation of string addresses and network sequential IP addresses

In IPv4 environment, use int inet_aton (const char * cp, struct in_addr * np) to complete the conversion from string address to IP address. In IPv6 environment, use int inet_pton (int Af,const char * src,void * dst) with one more input parameter, using sample: inet_pton (AF_INET6,hostname,&snd_tcp_addr.sin6_addr)

On the contrary, when the IP address in the network order is converted to a string, char* inet_ntoa (struct in_addr_in) is used in IPv4, while in the IPv6 environment, the function const char* inet_ntop (int af, const void* src, char* dst, socklen_t cnt) is used, and the parameters are significantly changed. Use the sample:

Inet_ntop (PF_INET6, & rcv_udp_addr_sin6_addr,ip,sizeof (ip))

3.4 hostname and address translation (domain name resolution)

In the IPv4 environment, use the gethostbyname () or gethostbyaddr () function to implement the transformation; in the IPv6 environment, use the getnameinfo () or getaddrinfo () function to complete the transformation, which needs to include the following three header files:

# include

# include

# include

3.5 Multicast address constant

For the application of multicast, some constant definitions are added in the IPv6 environment, which are used when calling socket Socket API related functions. When code is refactored, the constants you focus on are shown in the following table:

Constant IPv6

IPV6_MULTICAST_IF sets a network interface as the interface for sending multicast datagrams

IPV6_MULTICAST_HOPS sets the range of hop for outgoing multicast datagrams.

IPV6_MULTICAST_LOOP if the multicast source itself belongs to the destination multicast group of the multicast data sent, and this option is set to 1, a loopback will be generated when it is sent locally. The default value for this option is 1

IPV6_JOIN_GROUP joins Multicast Group

IPV6_LEAVE_GROUP leaves Multicast Group

Sample code:

Rc=setsockopt (char) & gTtl,sizeof (gTt1))

The above technical key points are suitable for the refactoring of Socket software developed by Unix and CumberCraft + language under Linux platform. Compared with the Windows platform, the above points are basically appropriate (after all, the Winsock library is basically compatible with the standard Socket API definition), but compared with the Windows platform, you need to pay more attention to the following particularities when refactoring code:

(1) make sure the version of the Winsock library is 2.2 or above

For the Windows platform, IPv6 is supported only if the Winsock library is above 2.2.

(2) IP address information storage

In the Winsock2 library, a new SOCKADDR_STORGE structure is used to store address information, which shields the differences between IPv4 addresses and IPv6 addresses.

(3) socket Connect operation

In the Winsock2 library, in order to be compatible with IPv4 and IPv6, two new Connect functions (WSAConnectByName () and WSAConnectByList ()) are provided for establishing Socket connections. Compared with the standard connect () function, the advantage of these two Connect functions is that the IP address can be the address of IPv4 or IPv6.

In the process of field investigation, we also found that many IT systems do not directly use the original socket Socket API function or the encapsulated library on this basis, but use the third-party library when developing the Socket software using Cmax Candle + language. here we also analyze the commonly used third-party libraries for network programming.

Under the platforms of Linux, Unix and Windows, ACE (The Adaptive Comunication Environment) is a software package widely used for network application development. ACE software package has provided support for IPv6 since version 5.3. the class about IP address encapsulation provided in ACE package is ACE_INET_Addr, which shields the differences between different versions of IP addresses (IPv4, IPv6), and the member methods of the corresponding classes are compatible with different address versions. Therefore, the development of network applications based on ACE software package does not need to make this distinction (if the input address is the address of IPv4, then ACE_INET_Addr instantiates an instance with IPv4 characteristics, and the input address is the address of IPv6. Then ACE_INET_Addr instantiates instances with IPv6 features). In the process of refactoring code, you need to focus on whether the current ACE library has the ability to support IPv6, that is, to check whether there is a # ACE_HAS_IPV6 macro definition when compiling the ACE library.

Compared with the Socket application developed by Java Cure +, the Socket application developed with the Java programming language basically does not need to do any code refactoring from the IPv4 environment to the IPv6 environment. This is mainly due to the fact that the current version of JDK already provides support for IPv6 and that the differences in IP addresses (IPv4 and IPv6) have been shielded (the case of the JDK class library has been analyzed in the previous section), such as the following code:

Socket echosocket = new Socket ("hostip", 7)

If "hostip" corresponds to the address of IPv4, then echosocket is the Socket of type IPv4, and if "hostip" corresponds to the address of IPv6, then echosocket is of type IPv6, and one statement is suitable for both address types.

Although JDK provides a lot of convenience for us, so that our code basically does not need to be refactored, there are still two issues to consider:

1) operating system environment in which the Java virtual machine is running

You must ensure that the operating system environment in which JVM runs supports IPv6. Take the JVM of Sun as an example, to support IPv6, the requirements for the operating system are as follows:

(1) Solaris 8 or later

(2) Linux Kernel 2.1.2 or later (2.4.0 and above can be better supported)

(3) Windows XP sp1, Windows 2003 or later.

Compared with other JVM (such as IBM's JVM, Oracle's JRockit, etc.), you need to check the corresponding requirements for the host operating system.

2) how to divide the addresses of IP4 and IPv6

Although most applications developed by Java do not need to care about whether they use the address of IPv4 or IPv6, in some cases, such as the need to output the connected IP address information or the need to obtain the details of the address information, it is necessary to distinguish. We have previously analyzed that the address class used by the member functions of most classes in the java.net package is java.net.InetAddress, which is the parent class of the java.net.Inet4Address and java.net.Inet6Address classes, so you can check whether the address uses the address of IPv4 or IPv6 by checking the subclass type of java.net.InetAddress. The sample code is as follows:

InetAddress address = Socket.getInetAddress ()

If (address instanceof java.net.Inet4Address) {

Inet4Address address_ipv4 = (java.net.Inet4Address) address

Address_ipv4.getAddress ()

. / / address operation of the relevant IPv4

} else if (address instanceof java.net.Inet6Address) {

Inet6Address address_ipv6 = (java.net.Inet6Address) address

Address_ipv6.getScopeId ()

…… .. / / related IPv6 address operations

} else {

. .

}

Because the classes related to socket Socket provided by JDK are very perfect, it is rare to use third-party packages to develop Socket applications in Java language. Even those packages based on java.net package and applied to the third party of higher-level protocol applications, such as Net package in Apache Commons, which encapsulates the upper layer protocols such as ntp, smtp, ftp, telnet, pop3 and so on, inherits the characteristics of java.net package and uses java.net.InetAddress as the address type in the package, thus shielding the differences between IPv4 and IPv6, so that both IPv4 environment and IPv6 environment are supported functionally.

1.1.1.1. IPv4/IPV6 dual stack implementation

The previous analysis of this paper has concluded that the best solution for the evolution from IPv4 to IPv6 is that the IT system provides support for dual-stack applications. Here we will focus on how to make those interfaces based on socket Socket technology support dual-stack.

At present, most IT systems are application software based on the upper layer of the operating system. If the application system supports IPv4 and IPv6 dual stacks, the operating system must first support dual stacks, so it is a necessary condition to confirm or upgrade the operating system to support dual stacks before refactoring the application software.

It has been analyzed previously that the interfaces implemented based on socket Socket technology all adopt the same programming mode, that is, the typical client-server mode (Client-Server). For the server side, the server-side Socket should be able to listen to the bound IPv4 address and IPv6 address at the same time, so as to complete the service requests for different addresses. There are several ways to achieve this:

1) implement full address snooping

For the server, if the address that the server is listening to is bound to ":" (0.0.0.0 in IPv4), it will mean that the server listens to all the addresses in the address list of the system, that is, both the address of IPv4 and the address of IPv6 will be monitored by the server to provide services. For example, the following code:

Int port = 1099

ServerSocket server = new ServerSocket (port)

Socket s

While (true) {

S = server.accept ()

DoClientStuff (s)

}

The server will listen on port 1099 of all addresses in the address list (regardless of IPv4 address or IPv6 address). No matter whether the client accesses the address of IPv4 or IPv6, as long as the port is 1099, it will get server-side services.

Obviously, this pattern is the simplest refactoring pattern.

2) IPv4-compatible IPv6 address

If the IPv6 address that the server is listening to is a compatible address (address mode is:: w.x.y.z) or an address mapped by IPv4 (address mode is:: ffff:w.x.y.z), then in dual-stack mode, the server is actually listening on two addresses, such as The IPv6 address that the server is bound to listen to is:: ffff:192.158.112.8, so in fact, the server listens to the address ":: ffff:192.158.112.8" of the IPv6, as well as the address of 192.158.112.8. The destination address of the client Socket access is either the IPv4 address of 192.158.112.8 or the IPv6 address of ":: ffff:192.158.112.8". The service can be provided by the server.

3) IPv4 address and IPv6 address are independent

The addresses that the server needs to listen to are two completely independent IPv4 addresses and IPv6 addresses. In this case, the dual-stack application support is completed by listening to two different addresses respectively. See the following sample code:

SOCKET ServerSocket[FD _ SETSIZE]

ADDRINFO AI0;// stores the address of IPv6

ADDRINFO AI1;// stores the address of IPv4

ServerSocket [0] = socket (AF_INET6, SOCK_STREAM,PF_INET6)

ServerSocket [1] = socket (AF_INET, SOCK_STREAM,PF_INET)

. ..

Bind (ServerSocket [0], AI0- > ai_addr,AI0- > ai_addrlen)

Bind (ServerSocket [1], AI1- > ai_addr,AI1- > ai_addrlen)

.

Select (2, & ServerSet, 0,0,0); / / select () system call: asynchronous Imax O multiplex

If (FD_ISSET (ServerSocket [0], & ServerSet)) {

/ / IPv6 connection sockv6 = accept (… (.)

…… .

}

If (FD_ISSET (ServerSocket [1], & ServerSet)) {

/ / IPv4 connection sockv4 = accept (… .)

... ..

}

Obviously, this pattern is a more complex refactoring pattern.

Compared with the complex refactoring scheme on the server side, the transformation of the client side will be relatively simple. In a system that supports dual-stack applications, each client Socket connection instance will only choose between IPv4 mode and IPv6 mode. This choice can be done through the corresponding configuration file, before each client Socket instance is created. Decide which type of Socket instance to create based on the server address type read from the configuration file (or the automatic analysis of the address format to obtain the type) configuration item. Compared with the client developed by Java, due to the good adaptability of JDK to IPv6 (which has been analyzed earlier), the code hardly needs to be refactored. Compared with the client developed by CBank +, it is necessary to use different address structures and parameters to create Socket instances according to the type of IP address on different servers (the key technologies section has been analyzed).

For systems with a single stack in the actual running environment, it is not advisable to develop different versions of IPv4 and IPv6. The usual solution (whether client or server) is similar to that of the client in a dual-stack environment, that is, selecting the profile option to determine whether the current instance is running in an IPv4 environment or an IPv6 environment.

On how to use Socket programming from IPv4 to IPv6 support to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Internet Technology

Wechat

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

12
Report