Python 取得 hostname 的方法

本篇介紹 Python 取得 hostname 的方法。

python3-get-hostname.py
1
2
3
4
5
6
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket

print(socket.gethostname())
print(socket.getfqdn(socket.gethostname()))

結果如下,

1
2
shengyu-PC
shengyu-PC

寫成函式的話,範例如下,

python3-get-hostname2.py
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket

def get_hostname():
hostname = socket.getfqdn(socket.gethostname())
return hostname

print(get_hostname())

其它參考
python - what’s the difference between gethostname and getfqdn? - Stack Overflow
https://stackoverflow.com/questions/13931924/whats-the-difference-between-gethostname-and-getfqdn

其它相關文章推薦
Python 新手入門教學懶人包
Python 讀取 txt 文字檔
Python 寫檔,寫入 txt 文字檔
Python 讀取 csv 檔案
Python 寫入 csv 檔案
Python 讀寫檔案
Python 產生 random 隨機不重複的數字 list
Python PyAutoGUI 使用教學
Python OpenCV resize 圖片縮放