FastDFS基础使用
maven坐标
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.27.2</version>
</dependency>
配置文件 application.yml
#配置fastdfs
fdfs:
tracker-list: ip:22122
fasdfs:
address: http://ip:4568/group1/
创建一个FastDFSUtils工具包
package com.bibibi.utils;
import cn.hutool.http.HttpConnection;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResource;
import cn.hutool.http.HttpResponse;
import com.bibibi.model.CondtionException;
import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.AppendFileStorageClient;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.mysql.cj.core.util.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.rmi.ConnectException;
import java.util.*;
import java.util.List;
/**
* @author victor_Yao
* @createDate 2022/12/30 15:39
*/
@Component
public class FastDFSUtils {
@Resource
private FastFileStorageClient fastFileStorageClient;
@Resource
private RedisTemplate<String, Object> restTemplate;
/**
* 断点上传
*/
@Resource
private AppendFileStorageClient appendFileStorageClient;
@Value("${fasdfs.address}")
private String address;//http://ip:4567/group1/
private static final String DEFAULT_GROUP_ONE = "group1";
private static final String PATH_KEY = "path_key_";
private static final String UPLOAD_SIZE_KEY = "upload_size_key_";
private static final String UPLOAD_NO_KEY = "upload_no_key_";
private static final int SLICE_SIZE = 1024 * 1024;
public String getFileType(MultipartFile file) {
if (file == null) {
throw new CondtionException("非法文件!!!");
}
String filename = file.getOriginalFilename();
Assert.notNull(filename, "");
int index = filename.lastIndexOf(".");
return filename.substring(index + 1);
}
/**
* 上传文件
*
* @param file
* @return
* @throws IOException
*/
public String uploadCommonFile(MultipartFile file) throws IOException {
Set<MetaData> metaDataSet = new HashSet<>();
String fileType = this.getFileType(file);
StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), fileType, metaDataSet);
return storePath.getPath();
}
/**
* 删除
*
* @param filePath
*/
public void deleteFile(String filePath) {
fastFileStorageClient.deleteFile(filePath);
}
/**
* 断点上传文件 分片
*/
public String uploadAppenderFile(MultipartFile file) throws IOException {
String fileType = this.getFileType(file);
StorePath appenderFile = appendFileStorageClient.uploadAppenderFile(DEFAULT_GROUP_ONE, file.getInputStream(), file.getSize(), fileType);
return appenderFile.getPath();
}
/**
* 追加数据
*
* @param file
* @param filePath
* @param offset
* @throws IOException
*/
public void modifyAppenderFile(MultipartFile file, String filePath, long offset) throws IOException {
appendFileStorageClient.modifyFile(DEFAULT_GROUP_ONE, filePath, file.getInputStream(), file.getSize(), offset);
}
/**
* 断点上传
* @param file 文件
* @param fileMd5 文件的MD5
* @param slices 上次文件的标识
* @param totoleSlices 总标识
* @return
* @throws IOException
*/
public String uploadFileBySlices(MultipartFile file, String fileMd5, Integer slices, Integer totoleSlices) throws IOException {
if (file == null || slices == null || totoleSlices == null) {
throw new CondtionException("参数异常");
}
//文件的路径
String pathKey = PATH_KEY + fileMd5;
//上传文件总的大小
String uploadedSizeKey = UPLOAD_SIZE_KEY + fileMd5;
//上传文件服务器的大小
String uploadNokey = UPLOAD_NO_KEY + fileMd5;
Object uploadSizeStr = restTemplate.opsForValue().get(uploadedSizeKey);
Long uploadedSize = 0L;
if (uploadSizeStr != null) {
uploadedSize = Long.valueOf(uploadSizeStr.toString());
}
if (slices == 1) {
//上传的第一个分片
String path = this.uploadAppenderFile(file);
if (StringUtils.isNullOrEmpty(path)) {
throw new ConnectException("上传失败");
}
restTemplate.opsForValue().set(pathKey, path);
restTemplate.opsForValue().set(uploadNokey, slices);
} else {
String path = String.valueOf(restTemplate.opsForValue().get(pathKey));
if (StringUtils.isNullOrEmpty(path)) {
throw new ConnectException("上传失败");
}
this.modifyAppenderFile(file, path, uploadedSize);
restTemplate.opsForValue().increment(uploadNokey);
}
//修改历史上传分片文件大小
uploadedSize += file.getSize();
restTemplate.opsForValue().set(uploadedSizeKey, uploadedSize);
//判断全部上完
Object uploadedNoStr = restTemplate.opsForValue().get(uploadNokey);
Integer uploadedNoInt = Integer.valueOf(String.valueOf(uploadedNoStr));
String resultStr = null;
if (uploadedNoInt.equals(totoleSlices)) {
//文件的的URL
resultStr = String.valueOf(restTemplate.opsForValue().get(pathKey));
//删除redis的key
List<String> keyList = Arrays.asList(uploadNokey, pathKey, uploadedSizeKey);
restTemplate.delete(keyList);
}
return resultStr;
}
/**
* 文件分开存
* @param multipartFile
* @throws IOException
*/
public void converFileToSlices(MultipartFile multipartFile) throws IOException {
String fileName = multipartFile.getOriginalFilename();
String[] fieName = fileName.split("\\.");
String fileType = this.getFileType(multipartFile);
File files = this.multipartFileToFile(multipartFile);
//获取文件的长度
long fileLength = files.length();
int count = 1;
for (int i = 0; i < fileLength; i += SLICE_SIZE) {
RandomAccessFile randomAccessFile = new RandomAccessFile(files, "r");
randomAccessFile.seek(i);
byte[] bytes = new byte[SLICE_SIZE];
int len = randomAccessFile.read(bytes);
String path = "D:/uploadtem/" + fieName[0] + "/" + count + "." + fileType;
File slice = new File(path);
FileOutputStream fileOutputStream = new FileOutputStream(slice);
fileOutputStream.write(bytes, 0, len);
fileOutputStream.close();
randomAccessFile.close();
count++;
}
//文件删除
files.delete();
}
//io流 转换File文件
public File multipartFileToFile(MultipartFile multipartFile) throws IOException {
String fileName = multipartFile.getOriginalFilename();
String[] fieName = fileName.split("\\.");
File files = File.createTempFile(fieName[0], "." + fieName[1]);
multipartFile.transferTo(files);
return files;
}
/**
* 解析文件的Md5
*
* @param multipartFile
* @return
* @throws IOException
*/
public String getFileMd5(MultipartFile multipartFile) throws IOException {
InputStream inputStream = multipartFile.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
inputStream.close();
return DigestUtils.md5Hex(baos.toByteArray());
}
/**
* 在线播放
* @param request
* @param response
* @param path
* @throws Exception
*/
public void viewVideoOnLineBySlices(HttpServletRequest request, HttpServletResponse response, String path) throws Exception {
FileInfo fileInfo = fastFileStorageClient.queryFileInfo(DEFAULT_GROUP_ONE, path);
long totoFileSize = fileInfo.getFileSize();
Assert.notNull(address, "参数异常");
String url = address + path;
Enumeration<String> headerNames = request.getHeaderNames();
Map<String, Object> handlers = new HashMap<>();
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
handlers.put(header, request.getHeader(header));
}
String rangeStr = request.getHeader("Range");
String[] range;
if (StringUtils.isNullOrEmpty(rangeStr)) {
rangeStr = "bytes=0-" + (totoFileSize - 1);
}
range = rangeStr.split("bytes=|-");
// 这里会拿到格式 "",0,554564
long begin = 0;
if (range.length >= 2) {
begin = Long.parseLong(range[1]);
}
long end = totoFileSize - 1;
if (range.length >= 3) {
end = Long.parseLong(range[2]);
}
long len = (end - begin) + 1;
String contentRange = "bytes " + begin + "-" + end + "/" + totoFileSize;
response.setHeader("Content-Range", contentRange);
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Type", "video/mp4");
response.setContentLength((int) len);
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
HttpUtil.get(url, handlers, response);
}
/**
* 网页下载文件
* @param url 地址 不需要Group
* @param response
*/
public void downLoadFile(String url, HttpServletResponse response) {
fastFileStorageClient.downloadFile(DEFAULT_GROUP_ONE, url, new DownloadCallback<String>() {
@Override
public String recv(InputStream ins) throws IOException {
String replace = UUID.randomUUID().toString().replace("-", "");
String fileName = replace + url.substring(url.lastIndexOf("."));
byte[] bytes = new byte[1024];
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream");
ServletOutputStream outputStream = response.getOutputStream();
try {
int len = 0;
while ((len = ins.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
}
} finally {
ins.close();
outputStream.flush();
outputStream.close();
}
return "success";
}
});
}
}
在线播放视频中的请求参数
HttpUtil.java
package com.bibibi.utils;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;
/**
* Http请求工具类
*/
public class HttpUtil {
private static final String CONTENT_TYPE_JSON = "application/json";
private static final String CONTENT_TYPE_URL_ENCODED = "application/x-www-form-urlencoded";
private static final String REQUEST_METHOD_POST = "POST";
private static final String REQUEST_METHOD_GET = "GET";
private static final Integer CONNECT_TIME_OUT = 120000;
/**
* http get请求
* @param url 请求链接
* @param params 请求参数
*/
public static HttpResponse get(String url, Map<String, Object> params) throws Exception {
String getUrl = buildGetRequestParams(url, params);
URL urlObj = new URL(getUrl);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoInput(true);
con.setRequestMethod(REQUEST_METHOD_GET);
con.setConnectTimeout(CONNECT_TIME_OUT);
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
/**
* http get请求 可以配置请求头
* @param url 请求链接
* @param params 请求参数
*/
public static HttpResponse get(String url,
Map<String, Object> params,
Map<String, Object> headers) throws Exception {
String getUrl = buildGetRequestParams(url, params);
URL urlObj = new URL(getUrl);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoInput(true);
con.setRequestMethod(REQUEST_METHOD_GET);
con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON);
con.setConnectTimeout(CONNECT_TIME_OUT);
//设置请求头
for(Entry<String, Object> entry : headers.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
con.setRequestProperty(key, value);
}
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
/**
* http get请求 返回输出流
* @param url 请求链接
* @param headers 请求头
* @param response 响应
*/
public static OutputStream get(String url,
Map<String, Object> headers,
HttpServletResponse response) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoInput(true);
con.setRequestMethod(REQUEST_METHOD_GET);
con.setConnectTimeout(CONNECT_TIME_OUT);
for(Entry<String, Object> entry : headers.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
con.setRequestProperty(key, value);
}
con.connect();
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
OutputStream os = response.getOutputStream();
int responseCode = con.getResponseCode();
byte[] buffer = new byte[1024];
if(responseCode >=200 && responseCode <300) {
int i = bis.read(buffer);
while (( i != -1)) {
os.write(buffer,0,i);
i = bis.read(buffer);
}
bis.close();
}
bis.close();
con.disconnect();
return os;
}
/**
* http post请求,请求参数使用map进行封装
* @param url 请求链接地址
* @param params 请求参数
*/
public static HttpResponse postJson(String url, Map<String, Object> params) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON);
con.setRequestMethod(REQUEST_METHOD_POST);
con.setConnectTimeout(CONNECT_TIME_OUT);
String json = JSONObject.toJSONString(params);
con.connect();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write(json);
outputStreamWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
outputStreamWriter.close();
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
/**
* http post请求,请求参数使用json字符串
* @param url 请求链接地址
*/
public static HttpResponse postJson(String url, String json) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON);
con.setRequestMethod(REQUEST_METHOD_POST);
con.setConnectTimeout(CONNECT_TIME_OUT);
con.connect();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write(json);
outputStreamWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
outputStreamWriter.close();
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
/**
* http post请求,请求参数使用json字符串, 可以配置请求头
* @param url 请求链接地址
* @param params 请求参数
*/
public static HttpResponse postJson(String url,
Map<String, Object> params,
Map<String, Object> headers) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", CONTENT_TYPE_JSON);
//设置请求头
for(Entry<String, Object> entry : headers.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
con.setRequestProperty(key, value);
}
con.setRequestMethod(REQUEST_METHOD_POST);
con.setConnectTimeout(CONNECT_TIME_OUT);
String json = JSONObject.toJSONString(params);
con.connect();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write(json);
outputStreamWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
outputStreamWriter.close();
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
/**
* http post请求,请求参数形式为url-encoded
* @param url 请求链接地址
* @param params 请求参数
*/
public static HttpResponse postUrlEncoded(String url,
Map<String, Object> params) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", CONTENT_TYPE_URL_ENCODED);
con.setRequestMethod(REQUEST_METHOD_POST);
con.setConnectTimeout(CONNECT_TIME_OUT);
con.connect();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
String postParam = buildPostFormOrUrlEncodedParams(params);
outputStreamWriter.write(postParam);
outputStreamWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
outputStreamWriter.close();
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
/**
* http post请求,请求参数形式为form-data
* @param url 请求链接地址
* @param params 请求参数
*/
public static HttpResponse postFormData(String url,
Map<String, Object> params) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod(REQUEST_METHOD_POST);
con.setConnectTimeout(CONNECT_TIME_OUT);
con.connect();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
String postParam = buildPostFormOrUrlEncodedParams(params);
outputStreamWriter.write(postParam);
outputStreamWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
outputStreamWriter.close();
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
/**
* http post请求,请求参数形式为form-data, 可以设置请求头
* @param url 请求链接地址
* @param params 请求参数
*/
public static HttpResponse postFormData(String url,
Map<String, Object> params,
Map<String, Object> headers) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod(REQUEST_METHOD_POST);
con.setConnectTimeout(CONNECT_TIME_OUT);
con.setRequestProperty("Content-Type", CONTENT_TYPE_URL_ENCODED);
//设置请求头
for(Entry<String, Object> entry : headers.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
con.setRequestProperty(key, value);
}
con.connect();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
String postParam = buildPostFormOrUrlEncodedParams(params);
outputStreamWriter.write(postParam);
outputStreamWriter.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
String response = writeResponse(responseCode,br);
outputStreamWriter.close();
br.close();
String cookie = con.getHeaderField("Set-Cookie");
con.disconnect();
return new HttpResponse(responseCode,response, cookie);
}
private static String buildPostFormOrUrlEncodedParams(Map<String, Object> params) throws Exception {
StringBuilder postParamBuilder = new StringBuilder();
if(params != null && !params.isEmpty()) {
for (Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null) {
continue;
}
String value = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
postParamBuilder.append(entry.getKey()).append("=").append(value).append("&");
}
postParamBuilder.deleteCharAt(postParamBuilder.length() - 1);
}
return postParamBuilder.toString();
}
private static String buildGetRequestParams(String url, Map<String, Object> params) throws Exception {
StringBuilder sb = new StringBuilder(url);
if(params != null && !params.isEmpty()) {
sb.append("?");
for (Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null) {
continue;
}
String value = URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
sb.append(entry.getKey()).append("=").append(value).append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
private static String writeResponse(int responseCode, BufferedReader br) throws Exception {
StringBuilder responseSb = new StringBuilder();
String response;
if(responseCode >=200 && responseCode <300) {
String line;
while ((line = br.readLine()) != null) {
responseSb.append(line).append("\n");
}
response = responseSb.toString();
br.close();
}else {
response = responseSb.toString();
}
return response;
}
public static class HttpResponse {
private int statusCode;
private String body;
private String cookie;
public String getCookie() {
return cookie;
}
public void setCookie(String cookie) {
this.cookie = cookie;
}
public HttpResponse(int statusCode, String body){
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse(int statusCode, String body, String cookie){
this.statusCode = statusCode;
this.body = body;
this.cookie = cookie;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean isSuccess(){
return this.statusCode >= 200 && this.statusCode < 300;
}
@Override
public String toString() {
return "{\n\tstatusCode:" + statusCode + ",\n\tbody:" + body + "}";
}
}
}
IpUtils.java
package com.bibibi.utils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
* IP工具类
*/
public class IpUtil {
public static String getIP(HttpServletRequest httpServletRequest) {
String ip = httpServletRequest.getHeader("X-Forwarded-For");
if (ip != null && !"".equals(ip.trim())) {
int index = ip.indexOf(",");
if (index != -1) {
ip = ip.substring(0, index);
}
return ip;
} else {
ip = httpServletRequest.getHeader("X-Real-IP");
if (ip == null || "".equals(ip.trim())) {
ip = httpServletRequest.getRemoteAddr();
}
return ip;
}
}
public static String getLocalAddress() {
try {
InetAddress candidateAddress = null;
Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
Enumeration<InetAddress> inetAddrs = iface.getInetAddresses();
while (inetAddrs.hasMoreElements()) {
InetAddress inetAddr = inetAddrs.nextElement();
if (!inetAddr.isLoopbackAddress()) {
if (inetAddr.isSiteLocalAddress()) {
return inetAddr.getHostAddress();
}
if (candidateAddress == null) {
candidateAddress = inetAddr;
}
}
}
}
if (candidateAddress != null) {
return candidateAddress.getHostAddress();
} else {
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
return jdkSuppliedAddress.getHostAddress();
}
} catch (Exception var5) {
return "unkown";
}
}
}
注意:本文归作者所有,未经作者允许,不得转载