欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 获取服务器真实IP的实例

程序员文章站 2024-02-23 14:18:58
 java 获取服务器真实ip的实例 前言: 根据操作系统的不同,获取的结果不同,故需要区分系统,分别获取 实现代码: import java.i...

 java 获取服务器真实ip的实例

前言:

根据操作系统的不同,获取的结果不同,故需要区分系统,分别获取

实现代码:

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.io.printwriter;
import java.io.unsupportedencodingexception;
import java.net.httpurlconnection;
import java.net.inet4address;
import java.net.inetaddress;
import java.net.interfaceaddress;
import java.net.networkinterface;
import java.net.socketexception;
import java.net.url;
import java.net.urlconnection;
import java.net.urlencoder;
import java.net.unknownhostexception;
import java.util.arraylist;
import java.util.enumeration;
import java.util.iterator;
import java.util.list;
import java.util.map;
 
import javax.servlet.http.httpservletrequest;
 
import org.apache.http.httpentity;
import org.apache.http.namevaluepair;
import org.apache.http.client.clientprotocolexception;
import org.apache.http.client.httpclient;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.closeablehttpresponse;
import org.apache.http.client.methods.httppost;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.util.entityutils;
import org.springframework.http.httpmethod;
 
/**
 * 常用工具类
 *
 * @author 席红蕾
 * @date 2016-09-27
 * @version 1.0
 */
public class webtoolutils {
 
  /**
   * 获取本地ip地址
   *
   * @throws socketexception
   */
  public static string getlocalip() throws unknownhostexception, socketexception {
    if (iswindowsos()) {
      return inetaddress.getlocalhost().gethostaddress();
    } else {
      return getlinuxlocalip();
    }
  }
 
  /**
   * 判断操作系统是否是windows
   *
   * @return
   */
  public static boolean iswindowsos() {
    boolean iswindowsos = false;
    string osname = system.getproperty("os.name");
    if (osname.tolowercase().indexof("windows") > -1) {
      iswindowsos = true;
    }
    return iswindowsos;
  }
 
  /**
   * 获取本地host名称
   */
  public static string getlocalhostname() throws unknownhostexception {
    return inetaddress.getlocalhost().gethostname();
  }
 
  /**
   * 获取linux下的ip地址
   *
   * @return ip地址
   * @throws socketexception
   */
  private static string getlinuxlocalip() throws socketexception {
    string ip = "";
    try {
      for (enumeration<networkinterface> en = networkinterface.getnetworkinterfaces(); en.hasmoreelements();) {
        networkinterface intf = en.nextelement();
        string name = intf.getname();
        if (!name.contains("docker") && !name.contains("lo")) {
          for (enumeration<inetaddress> enumipaddr = intf.getinetaddresses(); enumipaddr.hasmoreelements();) {
            inetaddress inetaddress = enumipaddr.nextelement();
            if (!inetaddress.isloopbackaddress()) {
              string ipaddress = inetaddress.gethostaddress().tostring();
              if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                ip = ipaddress;
                system.out.println(ipaddress);
              }
            }
          }
        }
      }
    } catch (socketexception ex) {
      system.out.println("获取ip地址异常");
      ip = "127.0.0.1";
      ex.printstacktrace();
    }
    system.out.println("ip:"+ip);
    return ip;
  }
 
  /**
   * 获取用户真实ip地址,不使用request.getremoteaddr();的原因是有可能用户使用了代理软件方式避免真实ip地址,
   *
   * 可是,如果通过了多级反向代理的话,x-forwarded-for的值并不止一个,而是一串ip值,究竟哪个才是真正的用户端的真实ip呢?
   * 答案是取x-forwarded-for中第一个非unknown的有效ip字符串。
   *
   * 如:x-forwarded-for:192.168.1.110, 192.168.1.120, 192.168.1.130,
   * 192.168.1.100
   *
   * 用户真实ip为: 192.168.1.110
   *
   * @param request
   * @return
   */
  public static string getipaddress(httpservletrequest request) {
    string ip = request.getheader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) {
      ip = request.getheader("proxy-client-ip");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) {
      ip = request.getheader("wl-proxy-client-ip");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) {
      ip = request.getheader("http_client_ip");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) {
      ip = request.getheader("http_x_forwarded_for");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) {
      ip = request.getremoteaddr();
    }
    return ip;
  }
 
  /**
   * 向指定url发送get方法的请求
   *
   * @param url
   *      发送请求的url
   * @param param
   *      请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @return url 所代表远程资源的响应结果
   */
  // public static string sendget(string url, string param) {
  // string result = "";
  // bufferedreader in = null;
  // try {
  // string urlnamestring = url + "?" + param;
  // url realurl = new url(urlnamestring);
  // // 打开和url之间的连接
  // urlconnection connection = realurl.openconnection();
  // // 设置通用的请求属性
  // connection.setrequestproperty("accept", "*/*");
  // connection.setrequestproperty("connection", "keep-alive");
  // connection.setrequestproperty("user-agent", "mozilla/4.0 (compatible;
  // msie 6.0; windows nt 5.1;sv1)");
  // // 建立实际的连接
  // connection.connect();
  // // 获取所有响应头字段
  // map<string, list<string>> map = connection.getheaderfields();
  // // 遍历所有的响应头字段
  // for (string key : map.keyset()) {
  // system.out.println(key + "--->" + map.get(key));
  // }
  // // 定义 bufferedreader输入流来读取url的响应
  // in = new bufferedreader(new
  // inputstreamreader(connection.getinputstream()));
  // string line;
  // while ((line = in.readline()) != null) {
  // result += line;
  // }
  // } catch (exception e) {
  // system.out.println("发送get请求出现异常!" + e);
  // e.printstacktrace();
  // }
  // // 使用finally块来关闭输入流
  // finally {
  // try {
  // if (in != null) {
  // in.close();
  // }
  // } catch (exception e2) {
  // e2.printstacktrace();
  // }
  // }
  // return result;
  // }
 
  /**
   * 向指定 url 发送post方法的请求
   *
   * @param url
   *      发送请求的 url
   * @param param
   *      请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @return 所代表远程资源的响应结果
   */
  public static void sendpost(string pathurl, string name, string pwd, string phone, string content) {
    // printwriter out = null;
    // bufferedreader in = null;
    // string result = "";
    // try {
    // url realurl = new url(url);
    // // 打开和url之间的连接
    // urlconnection conn = realurl.openconnection();
    // // 设置通用的请求属性
    // conn.setrequestproperty("accept", "*/*");
    // conn.setrequestproperty("connection", "keep-alive");
    // conn.setrequestproperty("user-agent",
    // "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
    // // 发送post请求必须设置如下两行
    // conn.setdooutput(true);
    // conn.setdoinput(true);
    // // 获取urlconnection对象对应的输出流
    // out = new printwriter(conn.getoutputstream());
    // // 发送请求参数
    // out.print(param);
    // // flush输出流的缓冲
    // out.flush();
    // // 定义bufferedreader输入流来读取url的响应
    // in = new bufferedreader(
    // new inputstreamreader(conn.getinputstream()));
    // string line;
    // while ((line = in.readline()) != null) {
    // result += line;
    // }
    // } catch (exception e) {
    // system.out.println("发送 post 请求出现异常!"+e);
    // e.printstacktrace();
    // }
    // //使用finally块来关闭输出流、输入流
    // finally{
    // try{
    // if(out!=null){
    // out.close();
    // }
    // if(in!=null){
    // in.close();
    // }
    // }
    // catch(ioexception ex){
    // ex.printstacktrace();
    // }
    // }
    // return result;
    try {
      // 建立连接
      url url = new url(pathurl);
      httpurlconnection httpconn = (httpurlconnection) url.openconnection();
 
      // //设置连接属性
      httpconn.setdooutput(true);// 使用 url 连接进行输出
      httpconn.setdoinput(true);// 使用 url 连接进行输入
      httpconn.setusecaches(false);// 忽略缓存
      httpconn.setrequestmethod("post");// 设置url请求方法
      string requeststring = "客服端要以以流方式发送到服务端的数据...";
 
      // 设置请求属性
      // 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
      byte[] requeststringbytes = requeststring.getbytes("utf-8");
      httpconn.setrequestproperty("content-length", "" + requeststringbytes.length);
      httpconn.setrequestproperty("content-type", "  application/x-www-form-urlencoded");
      httpconn.setrequestproperty("connection", "keep-alive");// 维持长连接
      httpconn.setrequestproperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
      httpconn.setrequestproperty("accept-encoding", "gzip, deflate");
      httpconn.setrequestproperty("accept-language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
      httpconn.setrequestproperty("user-agent", "mozilla/5.0 (windows nt 6.1; win64; x64; rv:49.0) gecko/20100101 firefox/49.0");
      httpconn.setrequestproperty("upgrade-insecure-requests", "1");
 
      httpconn.setrequestproperty("account", name);
      httpconn.setrequestproperty("passwd", pwd);
      httpconn.setrequestproperty("phone", phone);
      httpconn.setrequestproperty("content", content);
 
      // 建立输出流,并写入数据
      outputstream outputstream = httpconn.getoutputstream();
      outputstream.write(requeststringbytes);
      outputstream.close();
      // 获得响应状态
      int responsecode = httpconn.getresponsecode();
 
      if (httpurlconnection.http_ok == responsecode) {// 连接成功
        // 当正确响应时处理数据
        stringbuffer sb = new stringbuffer();
        string readline;
        bufferedreader responsereader;
        // 处理响应流,必须与服务器响应流输出的编码一致
        responsereader = new bufferedreader(new inputstreamreader(httpconn.getinputstream(), "utf-8"));
        while ((readline = responsereader.readline()) != null) {
          sb.append(readline).append("\n");
        }
        responsereader.close();
      }
    } catch (exception ex) {
      ex.printstacktrace();
    }
  }
 
  /**
   * 执行一个http post请求,返回请求响应的html
   *
   * @param url
   *      请求的url地址
   * @param params
   *      请求的查询参数,可以为null
   * @return 返回请求响应的html
   */
  public static void dopost(string url, string name, string pwd, string phone, string content) {
    // 创建默认的httpclient实例.
    closeablehttpclient httpclient = httpclients.createdefault();
    // 创建httppost
    httppost httppost = new httppost(url);
    // 创建参数队列
    list<namevaluepair> formparams = new arraylist<namevaluepair>();
    formparams.add(new basicnamevaluepair("account", name));
    formparams.add(new basicnamevaluepair("passwd", pwd));
    formparams.add(new basicnamevaluepair("phone", phone));
    formparams.add(new basicnamevaluepair("content", content));
 
    urlencodedformentity uefentity;
    try {
      uefentity = new urlencodedformentity(formparams, "utf-8");
      httppost.setentity(uefentity);
      system.out.println("executing request " + httppost.geturi());
      closeablehttpresponse response = httpclient.execute(httppost);
      try {
        httpentity entity = response.getentity();
        if (entity != null) {
          system.out.println("--------------------------------------");
          system.out.println("response content: " + entityutils.tostring(entity, "utf-8"));
          system.out.println("--------------------------------------");
        }
      } finally {
        response.close();
      }
    } catch (exception e) {
      e.printstacktrace();
    } finally {
      // 关闭连接,释放资源
      try {
        httpclient.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
 
  }
}

以上就是java 获取服务去的ip的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!