vjame

优化代码是无止境的
随笔 - 65, 文章 - 9, 评论 - 26, 引用 - 0
数据加载中……

NetUtil 网络服务器端口辅助类


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 <= 0xFFFFreturn true;
        }

        
return false;
    }
    
    
public static void main(String arg[]){
        
boolean b = telnetStringPort("192.168.50.181","10242",1);
        
        System.out.println(b);
    }
}

posted on 2009-07-28 17:01 lanjh 阅读(309) 评论(0)  编辑  收藏 所属分类: Java App


只有注册用户登录后才能发表评论。


网站导航: