inotgo.com

This video is interpretive , So I hope you have read the content of this knowledge point , And after writing the corresponding code , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning



7 branch 9 second
This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers



Step 1 : IP address   
Step 2 : port   
Step 3 : Get native IP address   
Step 4 : ping Command   
Step 5 : use java Execute ping Command   
Step 6 : practice - Judge how many are available in this network segment ip address   
Step 7 : answer - Judge how many are available in this network segment ip address   

Every computer in the network must have a IP address ;
32 position ,4 Bytes , It is usually expressed in dotted decimal format , For example :192.168.1.100
127.0.0.1 It's fixed ip address , Represents the current computer , Equivalent to... In object-oriented " this"
IP address
Connect two computers , There is always a server , A client .
The communication between the server and the client is through the port . As shown in the figure :

ip the address is 192.168.1.100 Server via port 8080
With ip the address is 192.168.1.189 My client of 1087 Port communication
 port
 Get native IP address
package socket; import java.net.InetAddress; import java.net.UnknownHostException; public class TestSocket { public static void main(String[] args) throws UnknownHostException { InetAddress host = InetAddress.getLocalHost(); String ip =host.getHostAddress(); System.out.println(" Local machine ip address :" + ip); } }
package socket;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestSocket {

	public static void main(String[] args) throws UnknownHostException {
		InetAddress host = InetAddress.getLocalHost();
		String ip =host.getHostAddress();
		System.out.println(" Local machine ip address :" + ip);
	}
}
use ping Determine whether an address can reach
ping no java of api, yes windows A gadget in , Used to determine the response time of an address

As shown in the figure
ping 192.168.2.106 You can return the response time of this address time<1ms It means soon , LAN usually has this response time

ping 192.168.2.206 return Request timed out Indicates that no response has been returned for a long time , Basically, this address is not available
ping Command
Step 5 :

use java Execute ping Command

edit top fracture
With the help of Runtime.getRuntime().exec() You can run a windows of exe program
As shown in the figure , use java function ping 192.168.2.106, Return such a string
 use java  Execute ping Command
package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class TestSocket { public static void main(String[] args) throws IOException { Process p = Runtime.getRuntime().exec("ping " + "192.168.2.106"); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { if (line.length() != 0) sb.append(line + "\r\n"); } System.out.println(" The message returned by this command is :"); System.out.println(sb.toString()); } }
Step 6 :

practice - Judge how many are available in this network segment ip address

edit top fracture   Wrong posture , get half the results with double the effort ! Click to see the correct posture for the exercise
First get Get native IP address , For example, yes 192.168.2.100. Then the network segment ip The address is from 192.168.2.1 To 192.168.2.255
Then pass use java Execute ping Command Judge these ip Whether the address can be used , Put what can be used ip Print out
 practice - Judge how many are available in this network segment ip address
Step 7 :

answer - Judge how many are available in this network segment ip address

edit top fracture
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Viewing this answer will cost 5 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Viewing this answer will cost 5 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Account not activated Account not activated , Limited functionality . Please click activate
This video is interpretive , So I hope you have read the content of this answer , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning

5 branch 27 second This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers


In order to improve efficiency , Use multithreading to simultaneously ping. But if you turn it on 255 Threads , Because the network port is too crowded , Will be judged as unable to ping Pass .
So this example use java Built in thread pool , The number of connections in the thread pool cannot be too large , Started 15 Threads .

Wait for all threads to print out ping Yes ip address .
package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class TestSocket { public static void main(String[] args) throws IOException, InterruptedException { InetAddress host = InetAddress.getLocalHost(); String ip = host.getHostAddress(); String ipRange = ip.substring(0, ip.lastIndexOf('.')); System.out.println(" Local machine ip address :" + ip); System.out.println(" The network segment is : " + ipRange); List<String> ips = Collections.synchronizedList(new ArrayList<>()); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); AtomicInteger number = new AtomicInteger(); for (int i = 0; i < 255; i++) { String testIP = ipRange + "." + (i + 1); threadPool.execute(new Runnable() { @Override public void run() { boolean reachable = isReachable(testIP); if (reachable) // System.out.println(" Find connectable ip address :" + testIP); ips.add(testIP); synchronized (number) { System.out.println(" Already completed :" + number.incrementAndGet() + " individual ip Test "); } } }); } // Wait for all threads to end , Just close the thread pool threadPool.shutdown(); // Wait for the thread pool to close , But wait at most 1 An hour if (threadPool.awaitTermination(1, TimeUnit.HOURS)) { System.out.println(" as follows ip The address can be connected to "); for (String theip : ips) { System.out.println(theip); } System.out.println(" A total of :" + ips.size() + " Addresses "); } } private static boolean isReachable(String ip) { try { boolean reachable = false; Process p = Runtime.getRuntime().exec("ping -n 1 " + ip); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { if (line.length() != 0) sb.append(line + "\r\n"); } // When there is TTL When it appears , It means connected reachable = sb.toString().contains("TTL"); br.close(); return reachable; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } }


The official account of programming , Follow and get the latest tutorials and promotions in real time , thank you .


Q & A area    
2021-05-17 Practice the answers isReachable I can't understand the method ..
Cold noodles are not cold




. It's not mentioned in the tutorial , Confusing the child belongs to
private static boolean isReachable(String ip) {
        try {
            boolean reachable = false;
    
            Process p = Runtime.getRuntime().exec("ping -n 1 " + ip);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if (line.length() != 0)
                    sb.append(line + "\r\n");
            }
    
            // When there is TTL When it appears , It means connected 
            reachable = sb.toString().contains("TTL");
            br.close();
            return reachable;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2020-10-31 answer
lx213




Using thread pools is slow , Don't say one by one , Wait until the dishes are cold
public static void main(String[] args) throws IOException {
    	InetAddress host = InetAddress.getLocalHost();    // Create a native object 
    	String ip = host.getHostAddress();                // Get native ip address 
    	System.out.println(" Local machine ip the address is :" + ip);
    	String pre_ip = ip.substring(0,ip.lastIndexOf('.')+1);
    	ThreadPoolExecutor tpe = new ThreadPoolExecutor(100, 200 , 5, TimeUnit.SECONDS,
    			new LinkedBlockingDeque<Runnable>());     // Thread pool processing 
    	
    	for (int i = 1; i <= 255; i++)
    	{
    		final int j = i;
    		tpe.execute(new Runnable()
			{
				@Override
				public void run()
				{
					Process P;
					try
					{
						P = Runtime.getRuntime().exec("ping " + pre_ip + j);
						BufferedReader br = new BufferedReader(new InputStreamReader(P.getInputStream(), "GBK"));
			    		String temp = null;
			    		boolean tag = false;
			    		while ((temp = br.readLine())!=null)
						{
							if (temp.contains("TTL"))
							{
								tag = true;
								break;
							}
						}
			    		if (tag)
			    			System.out.println(" Available ip address :" + pre_ip + j);
					} catch (IOException e)
					{
						System.out.println("wocao?");
						e.printStackTrace();
					}
				}
			});
    		
    	}
    }
 
               


1 One answer

2667818514
Answer time :2021-04-10



The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2020-08-31 Test ip It feels better to add multithreading
2020-08-04 There is a problem with the output
2020-07-23 Mac Written , If you think there is anything better, please put it forward for me


Too many questions , Page rendering is too slow , To speed up rendering , Only a few questions are displayed on this page at most . also 23 Previous questions , please Click to view

Please... Before asking questions land
The question has been submitted successfully , Auditing . Please My question Check the question record at , thank you
about JAVA Intermediate - Network programming -IP address port Your questions

Try to provide Screenshot code and Abnormal information , Help to analyze and solve problems . You can also enter this station QQ Group communication : 496725845
Ask questions and try to provide complete code , Environment description , The more conducive to the recurrence of the problem , The faster your question can be answered .
Have questions about the code in the tutorial , Please provide which step , Which line is in doubt , This makes it easy to quickly locate the problem , Improve the speed at which questions are answered
In the thousands of questions that already exist , A considerable proportion , Because of the use of and webmaster Different versions of the development environment Resulting in , For example jdk, eclpise, idea, mysql,tomcat Wait, the version of the software is inconsistent .
Please use the same version as the webmaster , You can save yourself a lot of learning time . The webmaster sorted out the software versions used in teaching , It's all here , Convenient for everyone to download : /k/helloworld/helloworld-version/1718.html

Upload screenshot