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
···
相关推荐
wcy_10111 分钟前
QCoder智能生成Excel数据清洗与可视化代码
python·excel
蓝天居士8 分钟前
Linux网络驱动之Fixed-Link(29)
linux·运维·网络
切糕师学AI9 分钟前
家庭网络“双网关”现象解析与通用桥接配置指南
网络·网关
计算机安禾32 分钟前
【计算机网络】第2篇:端到端通信的形式化刻画——时延、带宽、丢包与吞吐量的数学模型
网络·计算机网络
灰子学技术39 分钟前
Envoy TCP 层面的 Metric 指标分析
开发语言·网络·网络协议·tcp/ip·php
财经资讯数据_灵砚智能42 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月2日
人工智能·python·信息可视化·自然语言处理·ai编程
skiy1 小时前
SpringBoot项目中读取resource目录下的文件(六种方法)
spring boot·python·pycharm
2601_956139421 小时前
集团品牌全案公司哪家专业
大数据·人工智能·python
ouliten1 小时前
[Triton笔记1]核心概念
笔记·python·深度学习·triton
清水白石0081 小时前
生成器不是性能银弹:什么时候该用 `yield` 省内存,什么时候它会拖慢 Python 数据处理吞吐?
开发语言·python·原型模式