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
···
相关推荐
乾元2 分钟前
安全官(CISO)的困惑:AI 投入产出比(ROI)的衡量
网络·人工智能·安全·网络安全·chatgpt·架构·安全架构
qq_334903155 分钟前
Python单元测试(unittest)实战指南
jvm·数据库·python
marsh02069 分钟前
13 openclaw数据验证与过滤:确保应用安全性的第一道防线
网络·数据库·ai·编程·技术
终端鹿15 分钟前
深度解析 WebSocket DevTools 插件
网络·websocket·网络协议
love530love24 分钟前
Duix-Avatar 去 Docker Desktop 本地化完整复盘
人工智能·pytorch·windows·python·docker·容器·数字人
character082528 分钟前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
IpdataCloud32 分钟前
交易所禁止某国IP:用离线库实现毫秒级拒绝+错误码返回
网络
weixin_4462608537 分钟前
小而强大的文件系统,大大提高微控制器的稳定性
linux·服务器·网络
站大爷IP37 分钟前
Python操作Redis:高效缓存设计与实战
python
smart margin39 分钟前
Python安装教程
开发语言·python