首页 / 操作系统 / Linux / Java InetAddress.getLocalHost() 在Linux里实现
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] = " ";
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,那么会使用默认的localhost2. 如果发现hostname的值是localhost 或者 localhost.localdomain, 根据自己的实际ip查找/etc/hosts中这个ip对应的hostname。3. 如果没有,则使用localhost 或者localhost.localdomain可以通过命令hostname xxx修改hostname,且不需要重启。