在servlet中取得本机的IP地址。用request.getLocalAddr()得到的总是127.0.0.1,我要得到的是真实的IP

解决方案 »

  1.   


    InetAddress addr = InetAddress.getLocalHost();
    String ip = addr.getHostAddress();
      

  2.   

    获得本机的所有IP public static String getLocalHostName() {
    String hostName;
    try {
    InetAddress addr = InetAddress.getLocalHost();
    hostName = addr.getHostName();
    } catch (Exception ex) {
    hostName = "";
    }
    return hostName;
    } public static String[] getAllLocalHostIP() {
    String[] ret = null;
    try {
    String hostName = getLocalHostName();
    if (hostName.length() > 0) {
    InetAddress[] addrs = InetAddress.getAllByName(hostName);
    if (addrs.length > 0) {
    ret = new String[addrs.length];
    for (int i = 0; i < addrs.length; i++) {
    ret[i] = addrs[i].getHostAddress();
    }
    }
    } } catch (Exception ex) {
    ret = null;
    }
    return ret;
    } public static void main(String[] args) {
    String[] localIP = getAllLocalHostIP();
    for (int i = 0; i < localIP.length; i++) {
    System.out.println(localIP[i]);
    }
    }
      

  3.   

    request.getLocalAddr()可以获得。 
    问题在于你是怎么访问服务器的, 估计你是在本机访问
    http://127.0.0.1/xx

    http://localhost/xxx这样都可能获得不了网卡的IP地址, 因为你根本没走网络。
    你可以用你的ip访问, 就可以获得正确的IP地址,或者你在其他机器试试
      

  4.   

    我在JSP里面用的这个:String loginIp = request.getRemoteAddr();
    你难道不可以用?
      

  5.   

    用用这个看看,httpServletRequest.getRemoteAddr();我用过,应该是可以的
      

  6.   

       public String getIp(){
         log.info("获取IP地址!");
         String ip=null;
         try{
             String info=InetAddress.getLocalHost().toString();
             int n=info.lastIndexOf("/");
             ip=info.substring(n+1);
            }catch(Exception e){
             log.info(e.getStackTrace());
            }
            return ip;
        }
      

  7.   

    public String getIp()
    {
      log.info("I need found ip");
      String ip=null;
    try
    {
    String info=InetAddress.getLocalHost().toString();
    int n=info.lastIndexOf("/");
    ip=info.subString(n+1);}
     catch(Exception e)
    {log.info(e.getStackTrace());
    }
    return ip;
    }