Skip to content

Instantly share code, notes, and snippets.

@linux-china
Created January 6, 2018 10:54
Show Gist options
  • Save linux-china/d9ea97c873d2766692223fe3c2891452 to your computer and use it in GitHub Desktop.
Save linux-china/d9ea97c873d2766692223fe3c2891452 to your computer and use it in GitHub Desktop.
Spring Boot to set server.address
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
/**
* spring boot admin client to get right ip
*
* @author linux_china
*/
@Configuration
public class TcpIpPropertySourceConfig {
@Autowired
private ServerProperties serverProperties;
@PostConstruct
public void init() throws Exception {
serverProperties.setAddress(getClientInetAddress());
}
InetAddress getClientInetAddress() throws Exception {
List<String> interfaces = Arrays.asList("eth0", "en0", "eth1", "en1", "eth2", "en2", "eth3", "en3", "wlan0");
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface networkInterface : Collections.list(nets)) {
if (interfaces.contains(networkInterface.getName())) {
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
if (!inetAddress.isAnyLocalAddress() && !(inetAddress instanceof Inet6Address)) {
return inetAddress;
}
}
}
}
return InetAddress.getLocalHost();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment