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
···
相关推荐
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ4 分钟前
aspect实现请求校验,但是WebSocket 端点类不能被 AOP 代理解决方案
网络·websocket·网络协议
数字护盾(和中)21 分钟前
从边界突破到物理破坏:APT 工控攻击链路与防御闭环
网络
如竟没有火炬23 分钟前
四数相加贰——哈希表
数据结构·python·算法·leetcode·散列表
Saniffer_SH28 分钟前
【每日一题】PCIe答疑 - 接大量 GPU 时主板不认设备或无法启动和MMIO的可能关系?
运维·服务器·网络·人工智能·驱动开发·fpga开发·硬件工程
大白的编程日记.28 分钟前
【计算网络学习笔记】Socket编程UDP实现简单聊天室
网络·笔记·学习
织元Zmetaboard33 分钟前
什么是态势感知大屏?
网络·数据库
背心2块钱包邮37 分钟前
第9节——部分分式积分(Partial Fraction Decomposition)
人工智能·python·算法·机器学习·matplotlib
木盏39 分钟前
三维高斯的分裂
开发语言·python
Web3VentureView42 分钟前
培养全球Web3人才:SYNBO商学院正式启动运营
网络·金融·重构·web3·区块链
a程序小傲1 小时前
京东Java面试被问:ZGC的染色指针如何实现?内存屏障如何处理?
java·后端·python·面试