Computer Network - Socket Experiment 1

Table of contents

1. Purpose of the experiment

2. Experimental content

3. Experimental environment

4. Experimental steps

1 InetAddress class

1.1 Introduction to the InetAddress class

1.2 Obtain the name and IP address of the local machine

1.3 Obtain all IP addresses of CSDN

2 URL class and URLConnection class

2.1 Introduction to the URL class

2.2 Introduction to the URLConnection class

2.3 Use the URL class to download a picture

2.4 Use the URL class to download the home page of Shenzhen University, and count the size of the downloaded web page file

appendix


1. Purpose of the experiment

Learn the basic concepts of network programming, the application of InetAddress, the application of URL, the application of URLConnection

2. Experimental content

Use of InetAddress class and URLConnection class

3. Experimental environment

  1. Windows operating system; Internet connection
  2. Eclipse+Java development environment

4. Experimental steps

1 InetAddress class

1.1 Introduction to the InetAddress class

Hosts on the Internet have two ways to represent addresses: domain names and IP addresses. Sometimes you need to find its corresponding IP address through the domain name, and sometimes you need to find the host name through the IP address. At this time, you can use the InetAddress class in the java.net package to complete the task.

The InetAddress class is an IP address encapsulation class, and it is also a strange class. It has no public construction method, and can only use some static methods of this class to obtain object instances, and then use these object instances to classify IP addresses or hosts. name to be processed. Some commonly used static methods of this class are as follows.

  • public static InetAddress getByName(String hostname): Create an InetAddress object based on the given hostname, which can be used to find the IP address of the host
  • public static InetAddress getByAddress (byte[] addr): Create an InetAddress object based on a given IP address, which can be used to find the host name corresponding to the IP
  • public static getHostAddress(): get IP address
  • public static getHostName(): Get the host name

In addition, this class has some other commonly used methods, as follows:

  • String getCanonicalHostName(): Gets the fully qualified domain name of this IP address
  • String getHostAddress(): returns the IP address string (in text form)
  • String getHostName(): Get the host name of this IP address
  • Int hashCode(): Returns the hash code for this IP address
  • Boolean isAnyLocalAddress(): Utility routine to check if InetAddress is a wildcard address
  • boolean isLinkLocalAddress(): Utility routine to check if InetAddress is a link-local address
  • boolean isLoopbackAddress(): Utility routine to check if InetAddress is a loopback address
  • Boolean isMCGlobal(): Utility routine to check if a multicast address has global scope
  • Boolean isMCLinkLocal(): Utility routine to check if a multicast address has link scope
  • Boolean isMCNodeLocal(): Utility routine to check if a multicast address has node scope
  • Boolean isMCOrgLocal(): Utility routine to check if a multicast address has organization scope
  • Boolean isMCSiteLocal(): Utility routine to check if a multicast address has site scope
  • Boolean isMulticastAddress(): Utility routine to check if InetAddress is an IP multicast address
  • Boolean isReachable(int timeout): Test whether the address can be reached
  • Boolean isReachable(NetworkInterface netif, int ttl, int timeout): Test whether the address can be reached
  • Boolean isSiteLocalAddress(): Utility routine to check if InetAddress is a site-local address
  • String toString(): Convert this IP address to String

1.2 Obtain the name and IP address of the local machine

Since we have learned some methods of the InetAddress class, here, we can directly use the getLocalHost method to obtain the local host name and local address.

Figure 1 The code to obtain the local machine name and address

As shown in Figure 1, the first line introduces the required java.net package. In the main function, first define the InetAddress class, and call the getLocalHost method to obtain the corresponding address, and finally output the result.

Figure 2 Get the output of the local machine name and address

       As shown in Figure 2, it is the output result. The host name of our computer is "YunhaoAlienware", and the address is 192.168.85.1

1.3 Obtain all IP addresses of CSDN

Since we have learned some methods of the InetAddress class, here, we can directly use the getAllByName method to store all IP addresses in a list and output them.

Figure 3 Get all IP address codes of CSDN

As shown in Figure 3, the first line introduces the required java.net package. In the main function, first define the array of the InetAddress class, and call the getAllByName method to obtain all IP addresses and store them in the array, and finally output the result.

Figure 4 Get the output of all IP addresses of CSDN

As shown in Figure 4, it is the output result. CSDN has only one IP address, which is 39.106.226.142.

2 URL class and URLConnection class

2.1 Introduction to the URL class

The URL class represents a Uniform Resource Locator, which is a pointer to a "resource" on the Internet. Resources can be simple files or directories, or references to more complex objects, such as queries to databases or search engines. Typically, a URL can be broken into several parts.

Such as https://www1.szu.edu.cn/board/view.asp, the URL example indicates that the protocol used is https (Hypertext Transfer Security Protocol) and the information resides on a computer named www1.szu.edu .cn host. The information name on the host is /board/view.asp. The exact meaning of this name on a host depends on the protocol and the host. This information is typically stored in a file, but can be generated at any time. This part of the URL is called the path part.

Additionally, the URL optionally specifies a "port", which is the port number used to establish a TCP connection to the remote host. If the port number is not specified, the protocol default port is used. For example, the default port for the http protocol is 80.

       The URL class has the following six construction methods:

  • URL(String spec): Create a URL object based on the String representation
  • URL(String protocol, String host, int port, String file): Create a URL object according to the specified protocol, host, port number and file
  • URL(String protocol, String host, int port, String file, URLStreamHandler handler): Create a URL object according to the specified protocol, host, port number, file and handler
  • URL(String protocol, String host, String file): Create a URL based on the specified protocol name, host name and file name
  • URL(URL context, String spec): Create a URL by parsing the given spec in the specified context
  • URL(URL context, String spec, URLStreamHandler handler): Creates a URL by parsing the given spec with the specified handler in the specified context

In addition, the URL class has some other commonly used methods, as follows:

  • boolean equals(Object obj): Compares whether this URL is equal to another object.
  • String getAuthority(): Get the authorization part of this URL.
  • Object getContent(): Get the content of this URL.
  • Object getContent(Class[] classes): Get the content of this URL.
  • int getDefaultPort(): Get the default port number of the protocol associated with this URL.
  • String getFile(): Get the file name of this URL.
  • String getHost(): Gets the hostname of this URL (if applicable).
  • String getPath(): Gets the path part of this URL.
  • int getPort(): Get the port number of this URL.
  • String getProtocol(): Get the protocol name of this URL.
  • String getQuery(): Gets the query part of this URL.
  • String getRef(): Gets the anchor (also called "reference") of this URL.
  • String getUserInfo(): Get the userInfo part of this URL.
  • int hashCode(): Creates an integer suitable for indexing into a hash table.
  • URLConnection openConnection(): Returns a URLConnection object that represents the connection to the remote object referenced by the URL.
  • URLConnection openConnection(Proxy proxy): Similar to openConnection(), the difference is that the connection is established through the specified proxy; protocol handlers that do not support the proxy method will ignore the proxy parameter and establish a normal connection.
  • InputStream openStream(): Opens a connection to this URL and returns an InputStream for reading from the connection.
  • boolean sameFile(URL other): Compares two URLs, excluding fragments.
  • protected void set(String protocol, String host, int port, String file, String ref): Set the field of URL.
  • protected void set(String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref): Set the specified 8 fields of the URL.
  • static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac): Sets the URLStreamHandlerFactory of the application.
  • String toExternalForm(): Constructs a string representation of this URL.
  • String toString(): Constructs a string representation of this URL.
  • URI toURI(): Returns the URI equivalent to this URL.

2.2 Introduction to the URLConnection class

URLConnection is an abstract class that represents an active connection to a resource specified by a URL. The openConnection() method in the URL class can generate a URLConnection object, and the instance of the URLConnection class can be used to read and write resources referenced by this URL. In network programming, JAVA's URLConnection is a commonly used class, which provides a very convenient interface. As long as the URL address of the host to be connected is provided, an HttpURLConnection object can be obtained by using the openConnection() method of the URL class. Among them, the HttpURLConnection class is a subclass of the URLConnection class, and then analyze the HTTP content on this basis to complete related tasks. In this way, the user does not have to consider the underlying implementation details, avoiding the cumbersome code writing of the Socket class, so it is more commonly used

       There is only one common construction method of the URLConnection class, which is to obtain the corresponding URLConnection class through the URL:

  • protected URLConnection(URL url)

After the remote object is established, the following methods are often used to obtain the corresponding value:

  • getContent: Get the content of this URL connection.
  • getHeaderField: Returns the value of the specified header field. If the calling connection sets the header field multiple times with different values, only the last value set is returned.
  • getInputStream: Returns the input stream read from this opened connection. When reading the returned input stream, if the read timeout is reached before data is available for reading, a SocketTimeoutException will be thrown.
  • getOutputStream: Returns the output stream written to this connection.

2.3 Use the URL class to download a picture

The URL class is often used to download network resources. The URL can get an object through the constructor (the constructor is the URL address), and the openStream() method of the object can get the InputStream object. After getting the InputStream, the resources on the website can be downloaded. The following is an example, using the URL class to download a picture on a website and save it locally.

Figure 5 Code to download pictures using URL

       As shown in Figure 5, the first two lines introduce the required packages, the 6th and 7th lines use the URL class to obtain the input stream, and the 9-13th line uses the loop to store the input stream into the local file.

Figure 6 Images downloaded using URL

       As shown in Figure 6, it is the picture downloaded using the URL.

2.4 Use the URL class to download the home page of Shenzhen University, and count the size of the downloaded web page file

Since we have learned some methods of the URL class, here, we can directly use the URL class to establish a connection, and combine the methods of the URLConnection class to obtain the files of the Shenda homepage by means of streams.

Figure 7 URL category to download the home page code of Shenzhen University

       As shown in Figure 7, the first three lines introduce the required packages. Lines 8 and 9 use the URL class and URLConnection class to establish a connection, line 11 uses the getInputStream method to obtain the corresponding input stream, and line 12 uses the file stream to create a file. Lines 13-17 then use a while loop to read the content into the file. The last 19-20 lines use the file to get the size of the corresponding html file.

Figure 8 The size of the acquired html file

Figure 9 Acquired HTML file

       As shown in Figure 9, the obtained homepage file of Shenzhen University is as shown in the figure; as shown in Figure 8, the size of the obtained html file is 92.9kb.

appendix

code show as below:

import java.io.*;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static void main(String[] args) throws IOException {
        //使用InetAddress类的方法获取本地机的名称和IP地址
        InetAddress address = InetAddress.getLocalHost();
        System.out.println("Localhost:" + address);

        //使用InetAddress类的方法获取网站www.csdn.net的IP地址,如果存在多个IP地址,要求全部返回
        InetAddress[] address_Arr = InetAddress.getAllByName("www.csdn.net");
        System.out.println("All the IP address about CSDN:");
        for (InetAddress inetAddress : address_Arr) {
            System.out.println(inetAddress.toString());
        }
        // 使用URL类下载深圳大学首页http://www.szu.edu.cn,并统计下载得到网页文件的大小
        URL url = new URL("https://www.szu.edu.cn");
        URLConnection url_connection = url.openConnection();

        InputStream in = url_connection.getInputStream();
        FileOutputStream fout = new FileOutputStream("szu_index.html");
        int a = 0;
        while (a > -1) {
            a = in.read();
            fout.write(a);
        }
        fout.close();
        File file = new File("szu_index.html");
        System.out.println("File size:" + file.length() / 1024.00 + "k");
    }
}

Guess you like

Origin blog.csdn.net/m0_46326495/article/details/124224045