【问题标题】:How can I loop through an IP address that is input by the user in python如何遍历用户在python中输入的IP地址
【发布时间】:2016-01-11 11:07:09
【问题描述】:

对不起,我是 python 新手,所以我想咨询一些事情。假设用户输入他的 IP ( 192.168.1.10 ),我想开始从他的输入 (192.168.1.10) 循环到子网 192.168.1.255/24 的末尾。

我在想一些事情

for i in range(256):
    IP = "192.168.1.%d" (i)
    print IP

但是我如何把他的意见放进去呢?任何指导都会有所帮助,谢谢。

干杯, 技术新手。

【问题讨论】:

    标签: python unix scripting ip range


    【解决方案1】:

    这应该对你有用,虽然我还没有测试过。

    ip=raw_input("Enter an ip address:")
    partToFetch= int(ip.split(".")[3])
    for i in range(partToFetch,256):
        print "192.168.1.{0}".format(str(i))
    

    【讨论】:

      【解决方案2】:

      假设您使用类似的初始 IP 地址

      IP = raw_input('Enter your IP:')
      

      你可以重做你的循环

      for i in range(256):
          print(IP[:IP.rfind('.')] + '.' + i)
      

      【讨论】:

        【解决方案3】:

        在 Python 3.3 中使用 ipaddress 模块。您可以使用index into a subnet as a list 的地址:

        >>> import ipaddress
        >>> subnet = ipaddress.ip_network('192.168.1.0/24')
        >>> for i in range(10, 256):
        >>>     print(subnet[i])
        192.168.1.10
        192.168.1.11
        ...
        192.168.1.254
        192.168.1.255
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-19
          • 1970-01-01
          • 2020-12-28
          • 2014-07-15
          • 1970-01-01
          相关资源
          最近更新 更多