文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

服务器的真实IP怎么利用java进行获取

2023-05-31 07:38

关注

这篇文章将为大家详细讲解有关服务器的真实IP怎么利用java进行获取,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

实现代码:

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; public class WebToolUtils {     public static String getLocalIP() throws UnknownHostException, SocketException {    if (isWindowsOS()) {      return InetAddress.getLocalHost().getHostAddress();    } else {      return getLinuxLocalIp();    }  }     public static boolean isWindowsOS() {    boolean isWindowsOS = false;    String osName = System.getProperty("os.name");    if (osName.toLowerCase().indexOf("windows") > -1) {      isWindowsOS = true;    }    return isWindowsOS;  }     public static String getLocalHostName() throws UnknownHostException {    return InetAddress.getLocalHost().getHostName();  }     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;  }     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;  }     // public static String sendGet(String url, String param) {  // String result = "";  // BufferedReader in = null;  // try {  // String urlNameString = url + "&#63;" + param;  // URL realUrl = new URL(urlNameString);  // // 打开和URL之间的连接  // URLConnection connection = realUrl.openConnection();  // // 设置通用的请求属性  // connection.setRequestProperty("accept", "*  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", "**;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();    }  }     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();      }    }   }}

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 资料下载
  • 历年真题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯