歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java InetAddress.getLocalHost() 在Linux裡實現

Java InetAddress.getLocalHost() 在Linux裡實現

日期:2017/3/1 10:06:03   编辑: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] = '\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,且不需要重啟。

Copyright © Linux教程網 All Rights Reserved