package com.strongit.emp.common.utils;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//TODO doc
public class NetUtil {
    public static boolean telnetStringPort(String ip, String port, int timeout) {
        if (port == null || !isValidPort(port)) {
            return NetUtil.ping(ip, timeout);
        }
        return NetUtil.telnet(ip, Integer.valueOf(port.trim()).intValue(),
                timeout);
    }
    public static boolean ping(String ip, int timeout) {
        AssertUtil.assertNull("IP is null.", ip);
        
        try {
            return InetAddress.getByName(ip.trim()).isReachable(timeout);
        } catch (UnknownHostException e) {
            System.err.println("UnknownHostException:" + e.getMessage());
            return false;
        } catch (IOException e) {
            System.err.println("IOException:" + e.getMessage());
            return false;
        }
    }
    public static boolean telnet(String ip, int port, int timeout) {
        AssertUtil.assertNull("IP is null.", ip);
        
        Socket server = null;
        try {
            server = new Socket();
            server.connect(new InetSocketAddress(ip.trim(), port), timeout);
            return true;
        } catch (UnknownHostException e) {
            System.err.println("UnknownHostException:" + e.getMessage());
            return false;
        } catch (IOException e) {
            System.err.println("IOException:" + e.getMessage());
            return false;
        } finally {
            if (server != null)
                try {
                    server.close();
                } catch (IOException e) {
                    
                }
        }
    }
    public static boolean isValidPort(String port) {
        if (port != null && port.trim().matches("^[1-9][0-9]{0,3}$|^[1-5][0-9]{0,4}$|^6[0-5]{2}[0-3][0-5]$")) {
            int portInt = Integer.valueOf(port.trim()).intValue();
            if(portInt > 0 && portInt <= 0xFFFF) return true;
        }
        return false;
    }
    
    public static void main(String arg[]){
        boolean b = telnetStringPort("192.168.50.181","10242",1);
        
        System.out.println(b);
    }
}