网络编程

获取本机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("本机ip地址: "+ip);
    }
}
本机ip地址: 192.168.1.100

  

使用java 执行ping命令

借助 Runtime.getRuntime().exec() 可以运行一个windows的exe程序

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.1.100");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = bReader.readLine()) != null){
            if(line.length() != 0)
                sb.append(line + "
");
        }
        System.out.println("本次指令返回的消息是: ");
        System.out.println(sb.toString());
    }
}
本次指令返回的消息是: 
正在 Ping 192.168.1.100 具有 32 字节的数据:
来自 192.168.1.100 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.1.100 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.1.100 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.1.100 的回复: 字节=32 时间<1ms TTL=128
192.168.1.100 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 0ms,最长 = 0ms,平均 = 0ms

  

原文地址:https://www.cnblogs.com/exciting/p/10704275.html