1,获取linux服务器本机IP
package com.test;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* 得到本机ip地址
* @author WangSl
*/
public class NetUtil {
/**
* 得到本机地址,非127.0.0.1这样的
*/
private static String firstIPWithoutLocalhost = null;
/**
* 得到所有本机地址
*
* @return List<InetAddress>
*/
public static List<InetAddress> getAllHostAddress() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
List<InetAddress> addresses = new ArrayList<InetAddress>();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
addresses.add(inetAddress);
}
}
return addresses;
} catch (SocketException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
/**
* 得到第一个非127.0.0.1的,实际的ip地址
* @return String ip地址
*/
public static String getFirstIPWithoutLocalhost() {
if (firstIPWithoutLocalhost == null) {
List<InetAddress> colInetAddress = getAllHostAddress();
for (InetAddress address : colInetAddress) {
if (!address.isLoopbackAddress()&& address.getAddress().length == 4) {
firstIPWithoutLocalhost = address.getHostAddress();
break;
}
}
}
return firstIPWithoutLocalhost;
}
public static void main(String[] args) {
System.out.println(NetUtil.getFirstIPWithoutLocalhost());
}
}
2,获取Windows服务器本机IP
package com.test;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressObtainment_Windows {
String hostname;
String hostaddress;
void initialize() {
try {
InetAddress ia = InetAddress.getLocalHost(); // 获得本机网络地址对象
hostname = ia.getHostName(); // 获得对应主机名
hostaddress = ia.getHostAddress(); // 获得对应主机地址
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
InetAddressObtainment_Windows o1 = new InetAddressObtainment_Windows();
System.out.println(o1.hostname);
System.out.println(o1.hostaddress);
o1.initialize();
System.out.println(o1.hostname);
System.out.println(o1.hostaddress);
}
}