文章字数:416,阅读全文大约需要1分钟
获取服务器ip,之前一直用request.getHeader("Host")
获取。后来发现本机访问时获取到的是127.0.0.1
这个地址,而我需要的是其它地方也能访问到的地址。
方法
解析HostName
获取,直接InetAddress.getLocalHost().getHostAddress()
遍历网卡的地址(即本机所有ip地址),从中找到符合规则的。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.*; import java.util.function.Function;
import org.apache.commons.lang3.StringUtils;
public class test {
public static void main(String[] args) { try { InetAddress inet = InetAddress.getLocalHost(); String ipAddress = inet.getHostAddress(); System.out.println("单网卡获取ip地址 = " + ipAddress); } catch (UnknownHostException e) { e.printStackTrace(); }
try { String serverIp = getServerIpv4Address(ip -> { if (StringUtils.equals("127.0.0.1", ip.trim())) { return 0; } if (ip.matches( "^(127\\.0\\.0\\.1)|(localhost)|(10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(172\\.((1[6-9])|(2\\d)|(3[01]))\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})$")) { return 1; } return 2; });
System.out.println("遍历网卡地址选取ip = " + serverIp); } catch (Exception e) { e.printStackTrace(); } }
private static String getServerIpv4Address(Function<String, Integer> filter) throws Exception { Map<Integer, String> resMap = new HashMap<>(); Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); Enumeration<InetAddress> addresses = nif.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); if (addr instanceof Inet4Address) { String ip = addr.getHostAddress(); Integer index = filter.apply(ip); if (index != 0) { resMap.put(index, ip); } } } } Collection<Integer> collection = resMap.keySet(); if (collection.size() > 0) { Integer i = Collections.max(collection); return resMap.get(i); } return null; } }
|