package demo;
import java.net.InetAddress;
import org.apache.commons.lang.StringUtils;
/**
* 获取本机ip地址的最后段
* @author shenjie
* @date 2015-8-10
*
* */
public class GetIp {
public static int getLastSectionFromLocalIp() {
String ip = getLocalHostIp();
if (StringUtils.isBlank(ip)) {
new Exception("无法获取本地ip地址");
}
// 取ip的最后一段
int index = ip.lastIndexOf(".");
return Integer.parseInt(ip.substring(index + 1));
}
// 得到本机ip地址,如果无法获取本地的ip地址则返回""
public static String getLocalHostIp() {
InetAddress addr;
String ip;
try {
addr = InetAddress.getLocalHost();
ip = addr.getHostAddress();// 获得本机IP
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip = "";
}
return ip;
}
public static void main(String[] args) {
GetIp getIp = new GetIp();
System.out.println(getIp.getLastSectionFromLocalIp());
}
import java.net.InetAddress;
import org.apache.commons.lang.StringUtils;
/**
* 获取本机ip地址的最后段
* @author shenjie
* @date 2015-8-10
*
* */
public class GetIp {
public static int getLastSectionFromLocalIp() {
String ip = getLocalHostIp();
if (StringUtils.isBlank(ip)) {
new Exception("无法获取本地ip地址");
}
// 取ip的最后一段
int index = ip.lastIndexOf(".");
return Integer.parseInt(ip.substring(index + 1));
}
// 得到本机ip地址,如果无法获取本地的ip地址则返回""
public static String getLocalHostIp() {
InetAddress addr;
String ip;
try {
addr = InetAddress.getLocalHost();
ip = addr.getHostAddress();// 获得本机IP
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip = "";
}
return ip;
}
public static void main(String[] args) {
GetIp getIp = new GetIp();
System.out.println(getIp.getLastSectionFromLocalIp());
}
}
需要jar包 commons-lang-2.5.jar