美文网首页
网络连接(1)

网络连接(1)

作者: 老林_ | 来源:发表于2021-04-23 09:20 被阅读0次

    telnet 使用

    telnet time-a.nist.gov 13
    
    image.png

    java 使用Socket连接到服务器

    使用inputStream进行处理
    public static void getInfoUseInputStream(String url, int port) {
            try (Socket s = new Socket(url, port)) {
                InputStream inputStream = s.getInputStream();
                //对网络传来的输入流进行读取
                //如果这里不先进行读取则获取不到
                int firstByte = inputStream.read();
                int available = inputStream.available();
                while (available > 0) {
                    byte[] bytes = new byte[available + 1];
                    bytes[0] = (byte) firstByte;
                    inputStream.read(bytes, 1, available);
                    System.out.println(new String(bytes));
                    available = inputStream.available();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    使用Scanner进行处理 :逐段扫描文本
    
        public static void getInfoUseScanner(String url, int port) {
            try (Socket socket = new Socket(url, port);
                 Scanner in = new Scanner(socket.getInputStream(), "UTF-8")) {
                while (in.hasNextLine()) {
                    String line = in.nextLine();
                    System.out.print(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    打印出hostname对应的ip
    public static void main(String[] args) throws UnknownHostException {
            if(args.length>0){
                String host =args[0];
                try {
                    InetAddress[] addresses=InetAddress.getAllByName(host);
                    for(InetAddress a:addresses){
                        System.out.println(new String(a.getAddress()));
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }else {
                InetAddress localHostAddress=InetAddress.getLocalHost();
                byte[] address = localHostAddress.getAddress();
                // byte值为 -64,-88,0,-127,
                for(int a=0;a<address.length;a++){
                    System.out.print((0xff&address[a])+(a!=address.length-1?".":""));
                }
                //直接打印ip
                System.out.print("\n"+localHostAddress.getHostAddress());
            }
        }
    

    结果


    image.png

    相关文章

      网友评论

          本文标题:网络连接(1)

          本文链接:https://www.haomeiwen.com/subject/oklzlltx.html