Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 373|回复: 0

[网络编程学习]sun提供的ping代码

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-28 23:58:37 | 显示全部楼层 |阅读模式
    sun提供的ping源码,其实是通过连接端口测试设备是否工作,与传统的ICMP实现的ping完全不同.因为icmp是链路层协议,而java是工作在三层及三层之上,java要实现icmp ping只有采用JNI来实现,当前的有jpcap,类似于winpcap,libcap的开发包.

    source code:(线程同步及java.nio包中类的用法还是值得学习的).

    1. import java.io.*;
    2. import java.net.*;
    3. import java.nio.*;
    4. import java.nio.channels.*;
    5. import java.nio.charset.*;
    6. import java.util.*;
    7. import java.util.regex.*;
    8. public class Ping {
    9.     // The default daytime port
    10.     static int DAYTIME_PORT = 13;
    11.     // The port we"ll actually use
    12.     static int port = DAYTIME_PORT;
    13.     // Representation of a ping target
    14.     //
    15.     static class Target {
    16.         InetSocketAddress address;
    17.         SocketChannel channel;
    18.         Exception failure;
    19.         long connectStart;
    20.         long connectFinish = 0;
    21.         boolean shown = false;
    22.         Target(String host) {
    23.             try {
    24.                 address = new InetSocketAddress(InetAddress.getByName(host),
    25.                         port);
    26.             } catch (IOException x) {
    27.                 failure = x;
    28.             }
    29.         }
    30.         void show() {
    31.             String result;
    32.             if (connectFinish != 0)
    33.                 result = Long.toString(connectFinish - connectStart) + "ms";
    34.             else if (failure != null)
    35.                 result = failure.toString();
    36.             else
    37.                 result = "Timed out";
    38.             System.out.println(address + " : " + result);
    39.             shown = true;
    40.         }
    41.     }
    42.     // Thread for printing targets as they"re heard from
    43.     //
    44.     static class Printer extends Thread {
    45.         LinkedList pending = new LinkedList();
    46.         Printer() {
    47.             setName("Printer");
    48.             setDaemon(true);
    49.         }
    50.         void add(Target t) {
    51.             synchronized (pending) {
    52.                 pending.add(t);
    53.                 pending.notify();
    54.             }
    55.         }
    56.         public void run() {
    57.             try {
    58.                 for (;;) {
    59.                     Target t = null;
    60.                     synchronized (pending) {
    61.                         while (pending.size() == 0)
    62.                             pending.wait();
    63.                         t = (Target) pending.removeFirst();
    64.                     }
    65.                     t.show();
    66.                 }
    67.             } catch (InterruptedException x) {
    68.                 return;
    69.             }
    70.         }
    71.     }
    72.     // Thread for connecting to all targets in parallel via a single selector
    73.     //
    74.     static class Connector extends Thread {
    75.         Selector sel;
    76.         Printer printer;
    77.         // List of pending targets. We use this list because if we try to
    78.         // register a channel with the selector while the connector thread is
    79.         // blocked in the selector then we will block.
    80.         //
    81.         LinkedList pending = new LinkedList();
    82.         Connector(Printer pr) throws IOException {
    83.             printer = pr;
    84.             sel = Selector.open();
    85.             setName("Connector");
    86.         }
    87.         // Initiate a connection sequence to the given target and add the
    88.         // target to the pending-target list
    89.         //
    90.         void add(Target t) {
    91.             SocketChannel sc = null;
    92.             try {
    93.                 // Open the channel, set it to non-blocking, initiate connect
    94.                 sc = SocketChannel.open();
    95.                 sc.configureBlocking(false);
    96.                 boolean connected = sc.connect(t.address);
    97.                 // Record the time we started
    98.                 t.channel = sc;
    99.                 t.connectStart = System.currentTimeMillis();
    100.                 if (connected) {
    101.                     t.connectFinish = t.connectStart;
    102.                     sc.close();
    103.                     printer.add(t);
    104.                 } else {
    105.                     // Add the new channel to the pending list
    106.                     synchronized (pending) {
    107.                         pending.add(t);
    108.                     }
    109.                     // Nudge the selector so that it will process the pending
    110.                     // list
    111.                     sel.wakeup();
    112.                 }
    113.             } catch (IOException x) {
    114.                 if (sc != null) {
    115.                     try {
    116.                         sc.close();
    117.                     } catch (IOException xx) {
    118.                     }
    119.                 }
    120.                 t.failure = x;
    121.                 printer.add(t);
    122.             }
    123.         }
    124.         // Process any targets in the pending list
    125.         //
    126.         void processPendingTargets() throws IOException {
    127.             synchronized (pending) {
    128.                 while (pending.size() > 0) {
    129.                     Target t = (Target) pending.removeFirst();
    130.                     try {
    131.                         // Register the channel with the selector, indicating
    132.                         // interest in connection completion and attaching the
    133.                         // target object so that we can get the target back
    134.                         // after the key is added to the selector"s
    135.                         // selected-key set
    136.                         t.channel.register(sel, SelectionKey.OP_CONNECT, t);
    137.                     } catch (IOException x) {
    138.                         // Something went wrong, so close the channel and
    139.                         // record the failure
    140.                         t.channel.close();
    141.                         t.failure = x;
    142.                         printer.add(t);
    143.                     }
    144.                 }
    145.             }
    146.         }
    147.         // Process keys that have become selected
    148.         //
    149.         void processSelectedKeys() throws IOException {
    150.             for (Iterator i = sel.selectedKeys().iterator(); i.hasNext();) {
    151.                 // Retrieve the next key and remove it from the set
    152.                 SelectionKey sk = (SelectionKey) i.next();
    153.                 i.remove();
    154.                 // Retrieve the target and the channel
    155.                 Target t = (Target) sk.attachment();
    156.                 SocketChannel sc = (SocketChannel) sk.channel();
    157.                 // Attempt to complete the connection sequence
    158.                 try {
    159.                     if (sc.finishConnect()) {
    160.                         sk.cancel();
    161.                         t.connectFinish = System.currentTimeMillis();
    162.                         sc.close();
    163.                         printer.add(t);
    164.                     }
    165.                 } catch (IOException x) {
    166.                     sc.close();
    167.                     t.failure = x;
    168.                     printer.add(t);
    169.                 }
    170.             }
    171.         }
    172.         volatile boolean shutdown = false;
    173.         // Invoked by the main thread when it"s time to shut down
    174.         //
    175.         void shutdown() {
    176.             shutdown = true;
    177.             sel.wakeup();
    178.         }
    179.         // Connector loop
    180.         //
    181.         public void run() {
    182.             for (;;) {
    183.                 try {
    184.                     int n = sel.select();
    185.                     if (n > 0)
    186.                         processSelectedKeys();
    187.                     processPendingTargets();
    188.                     if (shutdown) {
    189.                         sel.close();
    190.                         return;
    191.                     }
    192.                 } catch (IOException x) {
    193.                     x.printStackTrace();
    194.                 }
    195.             }
    196.         }
    197.     }
    198.     public static void main(String[] args) throws InterruptedException,
    199.             IOException {
    200.         //args = new String[] { "3389", "10.0.0.222" }; 测试用
    201.         if (args.length < 1) {
    202.             System.err.println("Usage: java Ping [port] host...");
    203.             return;
    204.         }
    205.         int firstArg = 0;
    206.         // If the first argument is a string of digits then we take that
    207.         // to be the port number to use
    208.         if (Pattern.matches("[0-9]+", args[0])) {
    209.             port = Integer.parseInt(args[0]);
    210.             firstArg = 1;
    211.         }
    212.         // Create the threads and start them up
    213.         Printer printer = new Printer();
    214.         printer.start();
    215.         Connector connector = new Connector(printer);
    216.         connector.start();
    217.         // Create the targets and add them to the connector
    218.         LinkedList targets = new LinkedList();
    219.         for (int i = firstArg; i < args.length; i++) {
    220.             Target t = new Target(args[i]);
    221.             targets.add(t);
    222.             connector.add(t);
    223.         }
    224.         // Wait for everything to finish
    225.         Thread.sleep(2000);
    226.         connector.shutdown();
    227.         connector.join();
    228.         // Print status of targets that have not yet been shown
    229.         for (Iterator i = targets.iterator(); i.hasNext();) {
    230.             Target t = (Target) i.next();
    231.             if (!t.shown)
    232.                 t.show();
    233.         }
    234.     }
    235. }
    复制代码


       
         
         
          
          

            
          

            
          
         
       

      


    源码下载:http://file.javaxxz.com/2014/10/28/235836718.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-19 07:23 , Processed in 0.369872 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表