JAVA 和python 多网卡情况下获取正确的IP地址
要获取内网地址,可以尝试连接到10.255.255.255:1。如果连接成功,获取本地套接字的地址信息就是当前的内网IP。
python实现:
import socket
def extract_ip():
st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
st.connect(('10.255.255.255', 1))
IP = st.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
st.close()
return IP
Java:
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* 网络工具
* @author jqpeng
*/
public class NetUtils {
public static void main(String[] args) throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost.getHostAddress());
System.out.println("----------------下面才是正确的获取方式----------------");
localHost = getLocalHostExactAddress();
System.out.println(localHost.getHostAddress());
// System.out.println(localHost.getHostName());
}
public static InetAddress getLocalHostExactAddress() {
try {
DatagramSocket socket = new DatagramSocket();
socket.connect(InetAddress.getByName("10.255.255.255"), 1);
InetAddress address = socket.getLocalAddress();
socket.close();
return address;
} catch (UnknownHostException | SocketException e) {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
throw new RuntimeException(ex);
}
}
}
}
在java里,为了解决eureka获取client ip错误问题,可以重写InetUtils
/**
* 自定义InetUtils,重写findFirstNonLoopbackAddress方法,解决获取IP错误
* @author jqpeng
*/
@Slf4j
public class CustomInetUtils extends InetUtils {
public CustomInetUtils(InetUtilsProperties properties) {
super(properties);
log.info(properties.toString());
log.info("CustomInetUtils init");
}
@Override
public InetAddress findFirstNonLoopbackAddress() {
log.info("CustomInetUtils.findFirstNonLoopbackAddress");
return NetUtils.getLocalHostExactAddress();
}
}
用上面的类替换InetUtils :
@Bean
public InetUtils inetUtils(InetUtilsProperties inetUtilsProperties){
// 内网ip
inetUtilsProperties.setUseOnlySiteLocalInterfaces(true);
return new CustomInetUtils(inetUtilsProperties);
}