Java instance - get the IP address of the specified host
The following example demonstrates how to use the InetAddress.getByName() method of the InetAddress class to obtain the IP address of the specified host (web address):
import java.net.InetAddress; import java.net.UnknownHostException; public class GetIP { public static void main(String[] args) { InetAddress address = null; try { address = InetAddress.getByName("www.nowcoder.com"); } catch (UnknownHostException e) { System.exit(2); } System.out.println(address.getHostName() + "=" + address.getHostAddress()); System.exit(0); } }
The output of the above code is:
www.nowcoder.com=222.73.134.120
Java instance - check whether the port is used
The following example demonstrates how to detect whether a port is already in use:
import java.net.*; import java.io.*; public class Main { public static void main(String[] args) { Socket Skt; String host = "localhost"; if (args.length > 0) { host = args[0]; } for (int i = 0; i < 1024; i++) { try { System.out.println("see "+ i); Skt = new Socket(host, i); System.out.println("port " + i + " Already used"); } catch (UnknownHostException e) { System.out.println("Exception occured"+ e); break; } catch (IOException e) { } } } }
The output of the above code is:
...... View 17 View 18 View 19 View 20 View 21 Port 21 is already in use View 22 View 23 View 24 ......
Java instance - get the native ip address and hostname
The following example demonstrates how to use the getLocalAddress() method of the InetAddress class to obtain the native ip address and hostname:
import java.net.InetAddress; public class Main { public static void main(String[] args) throws Exception { InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local HostAddress: "+addr.getHostAddress()); String hostname = addr.getHostName(); System.out.println("Local host name: "+hostname); } }
The output of the above code is:
Local HostAddress: 192.168.1.4 Local host name: harsh
Java instance - get remote file size
The following example demonstrates how to get the size of a remote file:
import java.net.URL; import java.net.URLConnection; public class Main { public static void main(String[] args) throws Exception { int size; URL url = new URL( "http://static.nowcoder.com/images/res/logo/logo-v3.png"); URLConnection conn = url.openConnection(); size = conn.getContentLength(); if (size < 0) System.out.println("Unable to get file size."); else System.out.println("File size:" + size + " bytes"); conn.getInputStream().close(); } }
The output of the above code is:
File size: 11768 bytes
Java instance - Socket implementation of multithreaded server program
The following examples demonstrate how to use the accept() method of Socket class and the MultiThreadServer(socketname) method of ServerSocket class to implement multithreaded server programs:
import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class MultiThreadServer implements Runnable { Socket csocket; MultiThreadServer(Socket csocket) { this.csocket = csocket; } public static void main(String args[]) throws Exception { ServerSocket ssock = new ServerSocket(1234); System.out.println("Listening"); while (true) { Socket sock = ssock.accept(); System.out.println("Connected"); new Thread(new MultiThreadServer(sock)).start(); } } public void run() { try { PrintStream pstream = new PrintStream (csocket.getOutputStream()); for (int i = 100; i >= 0; i--) { pstream.println(i + " bottles of beer on the wall"); } pstream.close(); csocket.close(); } catch (IOException e) { System.out.println(e); } } }
The output of the above code is:
Listening Connected
Java instance - view the last modification time of the host specified file
The following example demonstrates how to view the last modification time of a host specified file:
import java.net.URL; import java.net.URLConnection; import java.util.Date; import java.text.SimpleDateFormat; public class Main { public static void main(String[] argv) throws Exception { URL u = new URL("http://127.0.0.1/test/test.html"); URLConnection uc = u.openConnection(); SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss"); uc.setUseCaches(false); long timestamp = uc.getLastModified(); System.out.println( "test.html Last modification time of file :" + ft.format(new Date(timestamp))); } }
The output of the above code is:
test.html Last modification time of file :2018-09-06 10:06:04
Java instance - use Socket to connect to the specified host
The following example demonstrates how to use the getInetAddress() method of the net.Socket class to connect to a specified host
import java.net.InetAddress; import java.net.Socket; public class WebPing { public static void main(String[] args) { try { InetAddress addr; Socket sock = new Socket("www.nowcoder.com", 80); addr = sock.getInetAddress(); System.out.println("connection to " + addr); sock.close(); } catch (java.io.IOException e) { System.out.println("cannot connect " + args[0]); System.out.println(e); } } }
The output of the above code is:
connection to http:/www.nowcoder.com/222.73.134.120
Java instance - Web page capture
The following example demonstrates how to grab a web page using the URL() constructor of the net.URL class:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.InputStreamReader; import java.net.URL; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://www.nowcoder.com"); BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter (new FileWriter("data.html")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); writer.write(line); writer.newLine(); } reader.close(); writer.close(); } }
The output result of the above code is (the source code of the web page is stored in the data.html file in the current directory):
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=11,IE=10,IE=9,IE=8"/>......
Java instance - get date information of URL response header
The following example demonstrates how to use the httpCon.getDate() method of HttpURLConnection to obtain the date information of the URL response header:
import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; public class Main{ public static void main(String args[]) throws Exception { URL url = new URL("http://www.nowcoder.com"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); long date = httpCon.getDate(); if (date == 0) System.out.println("Unable to get information."); else System.out.println("Date: " + new Date(date)); } }
The output of the above code is:
Date: Mon May 04 11:57:06 CST 2015
Java instance - get URL response header information
The following example demonstrates how to get the response header information of the specified URL:
import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] args) throws IOException{ URL url = new URL("http://www.nowcoder.com"); URLConnection conn = url.openConnection(); Map headers = conn.getHeaderFields(); Set<String> keys = headers.keySet(); for( String key : keys ){ String val = conn.getHeaderField(key); System.out.println(key+" "+val); } System.out.println( conn.getLastModified() ); } }
The output of the above code is:
Transfer-Encoding chunked null HTTP/1.1 200 OK Server Tengine/1.3.0 Connection keep-alive Vary Cookie Date Mon, 04 May 2015 03:54:05 GMT X-Pingback http://www.nowcoder.com/xmlrpc.php X-Powered-By PHP/5.3.15 Content-Type text/html; charset=UTF-8
Java instance - resolve URL
The following example demonstrates how to use the URL. Getprotocol(), URL. Getfile() and other methods of the net.URL class to resolve URL addresses:
import java.net.URL; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://www.nowcoder.com/html/html-tutorial.html"); System.out.println("URL yes " + url.toString()); System.out.println("The agreement is " + url.getProtocol()); System.out.println("The file name is " + url.getFile()); System.out.println("Host is " + url.getHost()); System.out.println("Path is " + url.getPath()); System.out.println("The port number is " + url.getPort()); System.out.println("The default port number is " + url.getDefaultPort()); } }
The output of the above code is:
URL yes http://www.nowcoder.com/html/html-tutorial.html The agreement is http The file name is /html/html-tutorial.html Host is www.nowcoder.com Path is /html/html-tutorial.html The port number is -1 The default port number is 80
Java instance - ServerSocket and Socket communication instance
The following example demonstrates how to implement the client to send a message to the server. The server receives the message and reads the output, and then writes it to the client. The client receives the output.
1. Establish server side
Establish communication server socket
The server establishes a Socket to receive client connections
Create an IO input stream to read the data sent by the client
Establish IO output and send data messages to the client
Server side code:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(8888); System.out.println("Start the server...."); Socket s = ss.accept(); System.out.println("client:"+s.getInetAddress().getLocalHost()+"Connected to server"); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //Read messages sent by clients String mess = br.readLine(); System.out.println("client:"+mess); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bw.write(mess+"\n"); bw.flush(); } catch (IOException e) { e.printStackTrace(); } } }
The output of the above code is:
Start the server....
2. Build client
Create Socket communication and set the IP and Port of the communication server
Establish IO output and send data messages to the server
Create an IO input stream to read the data message sent by the server
Client code:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; public class Client { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1",8888); //Build IO InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); //Send a message to the server bw.write("Test the communication between the client and the server, and the server returns the message to the client\n"); bw.flush(); //Read the message returned by the server BufferedReader br = new BufferedReader(new InputStreamReader(is)); String mess = br.readLine(); System.out.println("The server:"+mess); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
The output of the above code is:
Server: test the communication between the client and the server, and the server returns the message to the client