V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
loading
V2EX  ›  Python

判断一个ip是否在设置的ip段怎么写

  •  
  •   loading ·
    ycf · 2014-02-11 16:38:03 +08:00 via iPhone · 5833 次点击
    这是一个创建于 3731 天前的主题,其中的信息可能已经有所发展或是发生改变。
    目前写一个应用要针对ip进行简单限制,现在将配置文件写在xx.conf中用ConfigParser读取,现在我是这样写的:

    allowIp=['127.0.0.1','ip2','ip2']

    使用
    if getIp() not in allowIp:
    pass

    这样比较灵活,但如果一大段地址怎么写呢?如加上掩码的写法要怎么判断在不在里面呢?
    192.168.1.1/8
    11 条回复    1970-01-01 08:00:00 +08:00
    jasontse
        1
    jasontse  
       2014-02-11 16:39:47 +08:00 via iPad   ❤️ 1
    ip2long
    binux
        2
    binux  
       2014-02-11 16:42:53 +08:00
    http://zh.wikipedia.org/wiki/IPv4#.E5.9C.B0.E5.9D.80.E6.A0.BC.E5.BC.8F

    /8表示最后8未可以是任意值

    然后与一下就好了
    dorentus
        3
    dorentus  
       2014-02-11 17:09:19 +08:00
    @binux
    x.x.x.x/8 是表示除了前八位(二进制形式),后面的所有位可以是任意值。
    dorentus
        4
    dorentus  
       2014-02-11 17:15:35 +08:00
    @dorentus
    PS: x.x.x.x/8 里面的 8 其实就是子网掩码啦,/8 等同于 /255.0.0.0。
    Ever
        5
    Ever  
       2014-02-11 17:19:20 +08:00   ❤️ 1
    ipaddr和netaddr两个库都能很好的处理这个.
    loading
        6
    loading  
    OP
       2014-02-11 17:25:49 +08:00 via iPhone
    @jasontse
    @Ever 感谢


    @binux
    @dorentus
    @dorentus 这个怎么会不知道呢…
    dorentus
        7
    dorentus  
       2014-02-11 17:35:33 +08:00
    @loading
    嗯,我跑题了……

    不过不用别的工具的话,binux 的思路其实是可行的。
    loading
        8
    loading  
    OP
       2014-02-11 17:37:30 +08:00 via iPhone
    @binux
    @dorentus 嗯,就是太笨,太懒…
    nirocfz
        9
    nirocfz  
       2014-02-11 18:00:13 +08:00
    ipaddr 有个 Contains 方法
    magine
        10
    magine  
       2014-02-12 09:26:56 +08:00
    python 有个IPy包
    Mutoo
        11
    Mutoo  
       2014-02-12 09:42:26 +08:00
    ip/x 是末位子网掩码,不能满足你的需求的话,可以用完整的子网掩码,一般都可以达到目的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   818 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:14 · PVG 05:14 · LAX 14:14 · JFK 17:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.