热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

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

这篇文章主要介绍了java获取服务器真实IP的实例的相关资料,这里提供实现方法帮助大家学习理解这部分内容,需要的朋友可以参考下

 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 en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
        NetworkInterface intf = en.nextElement();
        String name = intf.getName();
        if (!name.contains("docker") && !name.contains("lo")) {
          for (Enumeration 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> 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 formparams = new ArrayList();
    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的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • Webmin远程命令执行漏洞复现及防护方法
    本文介绍了Webmin远程命令执行漏洞CVE-2019-15107的漏洞详情和复现方法,同时提供了防护方法。漏洞存在于Webmin的找回密码页面中,攻击者无需权限即可注入命令并执行任意系统命令。文章还提供了相关参考链接和搭建靶场的步骤。此外,还指出了参考链接中的数据包不准确的问题,并解释了漏洞触发的条件。最后,给出了防护方法以避免受到该漏洞的攻击。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 目录浏览漏洞与目录遍历漏洞的危害及修复方法
    本文讨论了目录浏览漏洞与目录遍历漏洞的危害,包括网站结构暴露、隐秘文件访问等。同时介绍了检测方法,如使用漏洞扫描器和搜索关键词。最后提供了针对常见中间件的修复方式,包括关闭目录浏览功能。对于保护网站安全具有一定的参考价值。 ... [详细]
  • Apache Shiro 身份验证绕过漏洞 (CVE202011989) 详细解析及防范措施
    本文详细解析了Apache Shiro 身份验证绕过漏洞 (CVE202011989) 的原理和影响,并提供了相应的防范措施。Apache Shiro 是一个强大且易用的Java安全框架,常用于执行身份验证、授权、密码和会话管理。在Apache Shiro 1.5.3之前的版本中,与Spring控制器一起使用时,存在特制请求可能导致身份验证绕过的漏洞。本文还介绍了该漏洞的具体细节,并给出了防范该漏洞的建议措施。 ... [详细]
  • 如何去除Win7快捷方式的箭头
    本文介绍了如何去除Win7快捷方式的箭头的方法,通过生成一个透明的ico图标并将其命名为Empty.ico,将图标复制到windows目录下,并导入注册表,即可去除箭头。这样做可以改善默认快捷方式的外观,提升桌面整洁度。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在Windows环境下如何配置php+apache环境,包括下载php7和apache2.4、安装vc2015运行时环境、启动php7和apache2.4等步骤。希望对需要搭建php7环境的读者有一定的参考价值。摘要长度为169字。 ... [详细]
  • 本文介绍了网页播放视频的三种实现方式,分别是使用html5的video标签、使用flash来播放以及使用object标签。其中,推荐使用html5的video标签来简单播放视频,但有些老的浏览器不支持html5。另外,还可以使用flash来播放视频,需要使用object标签。 ... [详细]
  • Java如何导入和导出Excel文件的方法和步骤详解
    本文详细介绍了在SpringBoot中使用Java导入和导出Excel文件的方法和步骤,包括添加操作Excel的依赖、自定义注解等。文章还提供了示例代码,并将代码上传至GitHub供访问。 ... [详细]
  • PHP组合工具以及开发所需的工具
    本文介绍了PHP开发中常用的组合工具和开发所需的工具。对于数据分析软件,包括Excel、hihidata、SPSS、SAS、MARLAB、Eview以及各种BI与报表工具等。同时还介绍了PHP开发所需的PHP MySQL Apache集成环境,包括推荐的AppServ等版本。 ... [详细]
author-avatar
勇往直前
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有