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
···
相关推荐
落羽凉笙1 分钟前
Python基础(4)| 详解程序选择结构:单分支、双分支与多分支逻辑(附代码)
android·服务器·python
档案宝档案管理5 分钟前
权限分级+加密存储+操作追溯,筑牢会计档案安全防线
大数据·网络·人工智能·安全·档案·档案管理
数据光子6 分钟前
【YOLO数据集】国内交通信号检测
人工智能·python·安全·yolo·目标检测·目标跟踪
携欢8 分钟前
portswigger靶场之修改序列化数据类型通关秘籍
android·前端·网络·安全
百***787512 分钟前
2026 优化版 GPT-5.2 国内稳定调用指南:API 中转实操与成本优化
开发语言·人工智能·python
yuanmenghao23 分钟前
CAN系列 — (4) Radar Header 报文:为什么它是 MCU 感知周期的“锚点”
网络·单片机·自动驾驶·信息与通信
Amelia11111126 分钟前
day48
python
小北方城市网29 分钟前
第 6 课:云原生架构终极落地|K8s 全栈编排与高可用架构设计实战
大数据·人工智能·python·云原生·架构·kubernetes·geo
智航GIS32 分钟前
10.1 网站防爬与伪装策略
python
Java后端的Ai之路34 分钟前
【AutoDL算力平台】-MobaXterm 连接 AutoDL 并上传文件资源(图文 + 实操)
服务器·网络·mobaxterm·autodl算力平台