Java InetAddress.getLocalHost() 在Linux里实现

2014-11-24 09:10:21 · 作者: · 浏览: 0

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,且不需要重启。