Skip to content

🐛 修改获取本机IP方法 #66

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 28, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,20 +1,49 @@
package org.minbox.framework.message.pipe.core.untis;

import org.minbox.framework.message.pipe.core.exception.MessagePipeException;

import java.net.InetAddress;
import java.net.*;
import java.util.Enumeration;

/**
* The internet address utils
*
* @author 恒宇少年
*/
public class InternetAddressUtils {
/**
* Obtain the IPv4 address according to the network card
*
* @return IPv4 address
*/
public static String getLocalIpByNetCard() {
try {
for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements(); ) {
NetworkInterface item = e.nextElement();
for (InterfaceAddress address : item.getInterfaceAddresses()) {
if (item.isLoopback() || !item.isUp()) {
continue;
}
if (address.getAddress() instanceof Inet4Address) {
Inet4Address inet4Address = (Inet4Address) address.getAddress();
return inet4Address.getHostAddress();
}
}
}
return InetAddress.getLocalHost().getHostAddress();
} catch (SocketException | UnknownHostException e) {
throw new RuntimeException(e);
}
}

public static String getLocalHost() {
/**
* Obtain Ipv4 address according to {@link InetAddress}
*
* @return Ipv4 address
*/
public static String getLocalIP() {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
return inetAddress.getHostAddress();
} catch (Exception e) {
throw new MessagePipeException(e.getMessage(), e);
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}