使用socke技术编写一段代码,完成获取本地主机的IP地址、子网掩码、网络关地址、域名服务器地址等信息的功能
时间: 2023-12-12 09:01:54 浏览: 112
下面是一个使用Python编写的获取本地主机信息的示例代码:
```python
import socket
import fcntl
import struct
# 获取本地主机名和IP地址
def get_host_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
# 获取本地主机的子网掩码
def get_netmask(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
netmask = socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x891b, # SIOCGIFNETMASK
struct.pack('256s', bytes(ifname[:15], 'utf-8'))
)[20:24])
return netmask
# 获取本地主机的网关地址
def get_gateway():
with open('/proc/net/route') as f:
for line in f:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
gateway = socket.inet_ntoa(struct.pack('<L', int(fields[2], 16)))
return gateway
# 获取本地主机的DNS服务器地址
def get_nameservers():
with open('/etc/resolv.conf') as f:
nameservers = []
for line in f:
fields = line.strip().split()
if fields[0] != 'nameserver':
continue
nameservers.append(fields[1])
return nameservers
if __name__ == '__main__':
hostname = socket.gethostname()
ip_address = get_host_ip()
netmask = get_netmask('eth0')
gateway = get_gateway()
nameservers = get_nameservers()
print('Hostname:', hostname)
print('IP Address:', ip_address)
print('Netmask:', netmask)
print('Gateway:', gateway)
print('Nameservers:', ', '.join(nameservers))
```
需要注意的是,本代码中获取子网掩码和网关地址的方式是基于Linux系统的,如果您是在其他操作系统上运行此代码,可能需要根据不同的系统做出相应的修改。
阅读全文