java 中的 InetAddress.getLocalHost()

在Inetaddress.getLocalHost()中最终调用的是Inet6AddressImpl.java(取决于你使用ipv4,还是ipv6) 中getLocalHostName的native代码
最终在native代码中
JNIEXPORT jstring JNICALL
Java_java_net_Inet6AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
char hostname[NI_MAXHOST+1];
hostname[0] = '\0';
if (JVM_GetHostName(hostname, MAXHOSTNAMELEN)) {
/* Something went wrong, maybe networking is not setup? */
strcpy(hostname, "localhost");
} else {
.....
}
}
JVM_GetHostName 的宏定义
JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))
JVMWrapper("JVM_GetHostName");
return hpi::get_host_name(name, namelen);
JVM_END
在linux中的函数
inline int hpi::get_host_name(char* name, int namelen){
return ::gethostname(name, namelen);
}
也就是通过调用linux 中的gethostname 内核函数
Linux 中的gethostname 实现
在linux中的hostname 是个变量,由系统初始话的时候, 在shell启动脚本 “/etc/rc.d/rc.sysinit” 中实现,主要是读取“/etc/sysconfig/network” 中的HOSTNAME的值
这里有几个注意点:
1. 如果文件中没有hostname,那么会使用默认的localhost
2. 如果发现hostname的值是localhost 或者 localhost.localdomain, 根据自己的实际ip查找/etc/hosts中这个ip对应的hostname。
3. 如果没有,则使用localhost 或者localhost.localdomain
可以通过命令
hostname xxx
修改hostname,且不需要重启。
下面是JAVA中判断是windows还是linux环境获取主机IP
/**
* 获得主机IP
*
* @return String
*/
public static boolean isWindowsOS(){
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if(osName.toLowerCase().indexOf("windows")>-1){
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 获取本机ip地址,并自动区分Windows还是linux操作系统
* @return String
*/
public static String getLocalIP(){
String sIP = "";
InetAddress ip = null;
try {
//如果是Windows操作系统
if(isWindowsOS()){
ip = InetAddress.getLocalHost();
}
//如果是Linux操作系统
else{
boolean bFindIP = false;
Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
if(bFindIP){
break;
}
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
//----------特定情况,可以考虑用ni.getName判断
//遍历所有ip
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = (InetAddress) ips.nextElement();
if( ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress() //127.开头的都是lookback地址
&& ip.getHostAddress().indexOf(":")==-1){
bFindIP = true;
break;
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if(null != ip){
sIP = ip.getHostAddress();
}
return sIP;
}
由最代码官方编辑于2014-7-19 12:44:19
最近浏览


