This is the eighth article in a series. For the first few, please click the link

Good News for programmers – An introduction to Apache Commons

Good news for Programmers – Apache Commons Lang

Programmer’s Gospel – Apache Commons IO

Good news for programmers – Apache Commons Codec

Programmer’s Gospel – Apache Commons Compress

Programmer’s Gospel – Apache Commons Exec

Programmer’s Gospel – Apache Commons Email

The Apache Commons Net library implements a number of basic Internet protocol clients. The purpose of the library is to provide basic protocol access, not higher levels of abstraction.

Commons-Net was originally a commercial Java library called NetComponents, originally created by ORO, Inc. Developed in the early days of Java. After the release of version 1.3.8 in 1998, the source code was donated to the Apache Software Foundation and is available under the Apache license. Since then, many programmers have contributed to the continued growth of Commons-Net. The numbering scheme for the current version is independent of the old version. That said, Commons Net 1.0 succeeded in replacing NetComponents 1.3.8.

The latest version of commons-net is currently 3.8.0, and the minimum requirement is Java7.

Maven coordinates are as follows:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.8.0</version>
</dependency>
Copy the code

Package structure is as follows:

org.apache.commons.net
org.apache.commons.net.bsd
org.apache.commons.net.chargen
org.apache.commons.net.daytime
org.apache.commons.net.discard
org.apache.commons.net.echo
org.apache.commons.net.finger
org.apache.commons.net.ftp
org.apache.commons.net.imap
org.apache.commons.net.io
org.apache.commons.net.nntp
org.apache.commons.net.ntp
org.apache.commons.net.pop3
org.apache.commons.net.smtp
org.apache.commons.net.telnet
org.apache.commons.net.tftp
org.apache.commons.net.time
org.apache.commons.net.util
org.apache.commons.net.whois
Copy the code

Here is a brief introduction to its structure and usage.

Overview 01.

At the heart of Commons-Net are Client classes that implement various network protocols. The two core abstract classes are SocketClient and DatagramSocketClient. SocketClient is the base class for all TCP implementations. DatagramSocketClient is the base class for all UDP implementations. The supported protocols are as follows (” S “means SSL/TLS is used for encryption, similar to HTTP and HTTPS) :

FTP/FTPS: File Transfer Protocol (FTP) is a Protocol in the TCP/IP Protocol group. The FTP protocol consists of an FTP server and an FTP client. The FTP server is used to store files. Users can use FTP clients to access resources on the FTP server through FTP. When developing a website, FTP protocol is usually used to upload Web pages or programs to the Web server. In addition, because of its high transmission efficiency, FTP is usually used to transfer large files over the network. The class that implements this protocol is FTPClient/FTPSClient

FTP over HTTP (experimental) : Uses HTTP to implement the FTP function. When FTP works in passive mode, not only 21 needs to be used as FTP control port (command), but also 20 needs to be used as FTP data port. Therefore, it is more difficult to configure the firewall. Therefore, it is better to use HTTP to transfer files. So we can use the original website combined with Alias method to add directory access control to achieve. The class that implements this protocol is FTPHTTPClient

NNTP: Network News Transfer Protocol (NNTP) is an Internet application Protocol used to read and post News articles to the Usenet. It is also responsible for transferring News between servers. The class that implements this protocol is NNTPClient

SMTP(S) : Simple Mail Transfer Protocol (SMTP) is a Protocol that provides reliable and effective email transmission. SMTP is a mail service based on THE FTP file transfer service. It is mainly used for the transfer of mail information between systems and the notification of mail. The class that implements this protocol is **SMTPClient****/**SMTPSClient

POP3(S) : POP3. The full name is Post Office Protocol – Version 3. The POP3 protocol allows an E-mail client to download mail from the server, but the actions of the client (such as moving mail, marking read, etc.) are not reported back to the server. The class that implements this protocol is POP3Client/POP3SClient

IMAP(S) : The Internet Message Access Protocol (IMAP), formerly known as the Interactive Mail Access Protocol (IMAP), is an application-layer Protocol. Its main function is that the mail client can obtain the mail information and download the mail from the mail server through this protocol. IMAP provides bidirectional communication between webmail and email clients. The operations of the clients are reported to the server. The operations performed on emails on the server also take corresponding actions. The class that implements this protocol is IMAPClient/IMAPSClient

Telnet: As a member of the TCP/IP protocol family, Telnet is the standard protocol and main mode for Internet remote login services. It provides the user with the ability to perform remote host work on a local computer. Use the Telnet program on the end-user’s computer to connect to the server. End users can enter commands in the Telnet program, which are run on the server as if they were entered directly on the server’s console. Telnet is a common method to remotely control a Web server. The class that implements this protocol is TelnetClient

TFTP: Trivial File Transfer Protocol (TFTP) is a Protocol used to Transfer simple files between clients and servers in the TCP/IP family. It provides an uncomplicated and inexpensive File Transfer service. The port number is 69. The class that implements this protocol is TFTPClient

Finger: Displays information about the user on the specified remote computer (usually a UNIX computer) running the Finger service or Daemon. The remote computer specifies the format and output to display user information. The class that implements this protocol is FingerClient

Whois: Whois is used to query the IP address and owner of a domain name. Simply put, whoIS is a database used to check whether a domain name has been registered and the details of the domain name (e.g., owner, registrar). In the early days whoIS query existed mostly as a command line interface, but now there are some online query tools for web pages that still rely on the WHOIS protocol. Command line tools are still widely used by system administrators. Whois usually uses TCP port 43. The WHOIS information for each domain name /IP is stored by the corresponding administrative authority. The class that implements this protocol is WhoisClient

Rexec/RCMD /rlogin: is a set of Unix commands, executed remotely, to login remotely, originated in the BSD system. To realize the agreement of the class is RExecClient/RCommandClient/RLoginClient

Time (rdate)/Daytime: The Daytime protocol is a TCP-based application and a useful debugging tool. It returns the current Time and date in a string format. Time Time Protocol is a network transport protocol defined in RFC 868. It is used to provide machine-readable date and time information. To realize the agreement of the class is TimeTCPClient/TimeUDPClient, DaytimeTCPClient/DaytimeUDPClient

Echo: Echo is a computer command. It can be based on TCP or UDP. The server detects whether there is a message on port 7. Routing is also the most commonly used data packet in the network. You can know which path the current connected node has by sending echo packets, and the length of the path can be obtained by round-trip time. Class is EchoTCPClient/EchoUDPClient implement the agreement

Discard: Discard protocol. Discard protocol is used to debug the network state. To realize the agreement of the class is * * * * DiscardTCPClient/DiscardUDPClient

NTP/SNTP: NTP server Network Time Protocol (NTP) is a Protocol used by a computer to synchronize Time with its server or clock source (such as quartz clock, GPS, etc.). The class that implements this protocol is ****NTPUDPClient

The client class diagram is as follows:

02. Tools and methods

Commons-net also provides a number of network-related utility classes to simplify some of our network handling, including the following

SubnetUtils: Performs some subnet calculations given a network address and subnet mask

TrustManagerUtils: TrustManager tool class

KeyManagerUtils: KeyManager utility class

SSLContextUtils: SSLContext tool class

Let’s look at a code example

1. The SSL

Java API:

// Use JDK native to get SSLContext
String key = "c:/client.jks";
String password = "123456"/ / key password
KeyStore keyStore = KeyStore.getInstance("JKS");  // Create a keystore to manage the keystore
keyStore.load(new FileInputStream(key), password.toCharArray());
// Create JKD key access library
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keyStore);
KeyManager[] kms = kmf.getKeyManagers();
TrustManager[] tms = tmf.getTrustManagers();
SSLContext ctx = SSLContext.getInstance("TLSv1"); // Supports SSLv2, SSLv3, TLSv1, TLSv1.1, and SSLv2Hello
ctx.init(kms, tms, null);
Copy the code

Commons Net

// Use commons-net related utility classes
String key = "c:/client.jks";
String password = "123456"; / / key password
File keyFile = new File(key);
KeyManager km = KeyManagerUtils.createClientKeyManager(keyFile, password);
TrustManager tm = TrustManagerUtils.getDefaultTrustManager(keyStore);
SSLContext ctx2 = SSLContextUtils.createSSLContext("TLSv1", km, tm);
Copy the code

2. Subnet tools

// There are two ways to initialize the Subnet tool class
// 1. Use the IP address and subnet mask
SubnetUtils subnet = new SubnetUtils("192.168.1.113"."255.255.255.0");
// 2. Use the CIDR address
SubnetUtils Subnet = new SubnetUtils("192.168.1.113/24"); // SubnetUtils subnet = new SubnetUtils("192.168.1.113/24");

// Get the network parameters
SubnetUtils.SubnetInfo si = subnet.getInfo();
// Obtain the IP address
si.getAddress(); / / 192.168.1.113
// Obtain the network address (the IP address and the subnet mask are calculated and, the result is the network address, that is, the host id all 0 is the network address)
si.getNetworkAddress(); / / 192.168.1.0
// Get the broadcast address (an address dedicated to sending to all workstations in the network simultaneously)
si.getBroadcastAddress(); / / 192.168.1.255
// Obtain the start IP address under the subnet
si.getLowAddress(); / / 192.168.1.1
// Get the end address under the subnet
si.getHighAddress(); / / 192.168.1.254
// Get the last address
si.getPreviousAddress(); / / 192.168.1.112
// Get the next address
si.getNextAddress(); / / 192.168.1.114
// Obtain the subnet mask
si.getNetmask(); / / 255.255.255.0
// Get the network address in CIDR format
si.getCidrSignature(); / / 192.168.1.113/24
// Obtain the maximum number of SUBNET IP addresses
si.getAddressCountLong(); / / 254
// Get the array of all IP addresses
si.getAllAddresses(); / / /... 192.168.1.1, 192.168.1.254
Copy the code

03. Network client

Commons-net provides a wide range of web clients, but here are a few simple examples:

1. WhoisClient

// Based on the TCP protocol
WhoisClient whoisClient = new WhoisClient();
try {
    // Use connect based on TCP
    whoisClient.connect(WhoisClient.DEFAULT_HOST);
    String host = whoisClient.query("baidu.com");
    System.out.println(host);
} finally {
    // Active disconnection is required for TCP
    whoisClient.disconnect();
}
Copy the code

2. TimeUDPClient

// Based on UDP
TimeUDPClient timeClient = new TimeUDPClient();
timeClient.setDefaultTimeout(3000);
InetAddress addr = InetAddress.getByName("time.nist.gov");
// UDP uses open
timeClient.open();
Date d = timeClient.getDate(addr);
System.out.println(DateFormatUtils.format(d, "yyyy-MM-dd HH:mm:ss.SSS"));
// UDP uses close to close the connection
timeClient.close();
Copy the code

I won’t give you an example of other simple protocols. Complex protocol (FTP) due to support more, doesn’t do length reason code examples, interested can go to the mirrors.tuna.tsinghua.edu.cn/apache//com… Download the source code here for Example.

04. Summary

Commons Net as a network toolkit, to achieve a lot of network protocol client, if there is a need to consider the use of, can also be based on the foundation of Net extension.

I look forward to your attention as I continue to introduce you to other useful utility libraries in The Commons section.