1.如何正确获得本机的IP地址.通过:InetAddress.getLocalHost();获得的是"xxxxxx/192.168.0.1"形式的,我怎样获得本机的IP地址形式:"192.168.0.1"?
2.在具有公网IP的计算机如何与局域网内的计算机建立socket链接?请考虑有防火墙的情况.

解决方案 »

  1.   

    public String[] getIpAddress(String hostname) throws SocketException,UnknownHostException {
    String[] get = null;
    InetAddress[] inetAddress = null;
    if (new CommonConvert().isEmpty(hostname)) {hostname = "localhost";}
    inetAddress = Inet4Address.getAllByName(hostname.toLowerCase());
    if (inetAddress.length > 0 && inetAddress != null) {
    get = new String[inetAddress.length];
    for (int i = 0;i<inetAddress.length;i++) {
    get[i] = inetAddress[i].getHostAddress();
    }
    }
    return get;
    }
      

  2.   

    楼上class:CommonConvert从哪里引入
      

  3.   

    try {
    InetAddress[] ia = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
    for(int i=0;i<ia.length;i++){
    System.out.print(ia[i].getHostAddress().toString());
    }
    } catch (UnknownHostException ex) {
    // TODO 自动生成 catch 块
    ex.printStackTrace();
    }