【问题标题】:store IP and subnet mask number in a variable and edit on it in Python将 IP 和子网掩码号存储在变量中并在 Python 中对其进行编辑
【发布时间】:2017-06-14 01:26:48
【问题描述】:

我想编写一个应用程序来帮助我确定 IP 类别并对其进行编辑,就像我使用 IP 类别“10.0.0.0”和子网掩码 255.0.0.0 我想让用户输入他的 IP 和SUBNET MASK 如上所述,我做了一个等式来告诉他他可以使用多少个 IP,在我的搜索过程中我得到了这个代码

import sys

sys.stdout.write("Enter IP address: ")
sys.stdout.flush()
ip = sys.stdin.readline()
print("you entered: " + ip)

但是当我使用它时,我无法通过该代码对 ip 进行任何编辑

import sys

sys.stdout.write("Enter IP address: ")
sys.stdout.flush()
ip = sys.stdin.readline()
a = ip + 1
print("you entered: " + ip + "and your IP will be : " + a)

显示错误:TypeError: must be str, not int

最后我想使该数字适用于对其进行编辑,并请解释您的代码以帮助我正确理解它。 在此先感谢

【问题讨论】:

  • sys.stdin.readline() 返回字符串。您不能将整数 (1) 添加到字符串 (ip)。为什么不使用input()
  • 那么我应该使用什么来代替 sys.stdin.readline() ?如果我使用输入,我该如何存储 xxx.xxx.xxx.xxx ?我知道输入应该检索一种类型的变量,如 int 或 string 或 float ...等
  • 你可以使用普通的input()函数。您不必这样做,这不是问题,但我不明白您为什么要使用 sys.stdin.readline() 而不是 input()
  • 我得到它时使用它,我看到有人使用该代码将IP存储在变量中,因为我使用它,你能给我一个关于如何使用常规输入的例子( ) 以及如何将 IP 存储在变量中以对其进行编辑

标签: python ip subnet


【解决方案1】:

在 Python 3.3 中,您可以使用 ipaddress — IPv4/IPv6 manipulation library

import sys
import ipaddress

sys.stdout.write("Enter IP address: ")
sys.stdout.flush()
ip = sys.stdin.readline().strip()   # remove the trailing '\n'
assigned_ip = ipaddress.IPv4Address(ip) + 1
print("You entered: " + ip + " and your IP will be: " + str(assigned_ip))

输出:

Enter IP address: 192.168.1.0
You entered: 192.168.1.0 and your IP will be: 192.168.1.1

【讨论】:

  • 你真是个天才,我想给你超过一百万个赞 :) 我使用了你的代码,它工作正常,非常感谢。
猜你喜欢
  • 2016-04-18
  • 2012-01-22
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 2013-07-18
  • 2018-08-16
  • 2018-04-03
相关资源
最近更新 更多