hostname的查看和设置

关于hostname

hostname是一台机器的网络身份标签,往往在安装系统的时候就设置好了。每一台机器应该有自己独一无二的身份id。

A hostname is a label assigned to a machine that identifies the machine on the network. Each device in the network should have a unique hostname.

The hostname can be a simple string containing alphanumeric characters, dots and hyphens. If the machine is connected to the Internet (such as web or mail server) it is recommended to use a fully qualified domain name (FQDN) as a system hostname. The FQDN consists of two parts, the hostname, and the domain name.
引用出处

查看与设置

  1. windows 中 我的电脑 属性设置

  2. linux系统中

$hostnamectl

lee@lee-VirtualBox:~$ hostnamectl
   Static hostname: lee-VirtualBox
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 113281522bfd49a08ac07ddd600dce03
           Boot ID: 40aa9fc060764230a9f0f60ad6531fed
    Virtualization: oracle
  Operating System: Ubuntu 20.04.3 LTS
            Kernel: Linux 5.15.0-71-generic
      Architecture: x86-64

sudo hostnamectl set-hostname mail.linuxize.com

使用python获取的方法

方法1(在Linux系统中会返回127.0.0.1):

python 复制代码
def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    return ip

方法2:

python 复制代码
import socket
import fcntl
import struct
 
def getip(ifname):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        netaddr = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15].encode('utf-8')))
        ipaddr = socket.inet_ntoa(netaddr[20:24])
    
        return ipaddr
    except OSError as oe:
        print ('No such device: ', ifname)
 
print ('lo: ', getip('lo'))
print ('eth0: ', getip('eth0'))
print ('eth1: ', getip('eth1'))

方法3,最为可靠:

python 复制代码
def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
        return ip
···
相关推荐
bst@微胖子29 分钟前
Python高级语法之selenium
开发语言·python·selenium
EasyNVR32 分钟前
EasyRTC:开启智能硬件与全平台互动新时代
网络·音视频·webrtc·p2p·智能硬件·视频监控
查理零世2 小时前
【蓝桥杯集训·每日一题2025】 AcWing 6118. 蛋糕游戏 python
python·算法·蓝桥杯
魔尔助理顾问3 小时前
一个简洁高效的Flask用户管理示例
后端·python·flask
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
红豆和绿豆6 小时前
如何发起http的请求,在系统中集成
网络·网络协议·http
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
Wlq04156 小时前
三种安全协议 IPSec & SSL & PGP
网络·安全·ssl
Liu-Eleven7 小时前
lwip和tcp/ip区别
网络·网络协议·tcp/ip
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python