描述:
我们有时候需要获取当前服务的IP和端口
实现:
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.util.Set;
//此类主要获取的是win上的ip和端口
public class IPPortUtil {
/**
* @return
* @throws MalformedObjectNameException
* 获取当前机器的端口号
*/
public static String getLocalPort() throws MalformedObjectNameException {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
String port = objectNames.iterator().next().getKeyProperty("port");
return port;
}
/**
* @return
* 获取当前机器的IP
*/
public static String getLocalIP() {
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}
byte[] ipAddr = addr.getAddress();
String ipAddrStr = "";
for (int i = 0; i < ipAddr.length; i++) {
if (i > 0) {
ipAddrStr += ".";
}
ipAddrStr += ipAddr[i] & 0xFF;
}
return ipAddrStr;
}
}
以上方法在Windows上获取ip和端口都是没有问题的,但在Linux服务器上就会出现问题,获取ip如果Linux没有对网络进行设置就会获取到127.0.0.1的问题和获取端口报错问题,此问题也给一些人带入坑中表示抱歉;以下为liunx机器获取ip和端口,在Windows也可以用。
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class GetIpAndPort {
//获取ip
public static String getLocalIP() {
String localIP = "127.0.0.1";
try {
OK:
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address) {
localIP = address.getHostAddress();
break OK;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return localIP;
}
//通过request获取ip
public static String getIp() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServerName();
}
//通过request获取端口
public static String getLocalPort() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServerPort() + "";
}
public static String getIpAndPort() {
return getLocalIP() + ":" + getLocalPort();
}
}