duanmen8491 2013-07-17 11:51
浏览 57
已采纳

找到两个IPv4地址之间的网络距离(不是地理距离)

Given an IPv4 address (needle) and an unsorted array of IPv4 addresses (haystack), how could I programmatically determine which single address in the given haystack is the closest (network-wise, NOT geographically) to the needle?

Since I don't have access to the netmask of every address, the solution should ignore netmasks and traceroute alike options.

All sorts of addresses are used, by which I mean: private, reserved, broadcast, lan and wan.

Any help in the form of theory, pseudo-code, python, php or perl is welcome.

The question Getting IP address list between two IP addresses is roughly similar, but it does quite cut it.

  • 写回答

3条回答 默认 最新

  • dougong1031 2013-07-17 13:12
    关注

    I'm still not quite sure what you're asking, but based on your comment

    @PeterGibson by closest I meant, 192.168.1.101 is closer to 192.168.56.1 than to 172.30.130.66 . And 192.168.1.254 is closer to 192.168.1.240 than to 192.168.2.1

    You could try the following python code for a distance function:

    import socket
    def dist(a, b):
        def to_num(addr):
            # parse the address string into integer quads
            quads = map(ord, socket.inet_aton(addr))
            # spread the quads out 
            return reduce(lambda x,y: x * 0x10000 + y, quads)
        return abs(to_num(a) - to_num(b))
    

    The numbers returned are fairly arbitrary, but should suffice for basic needs. I'm still not sure what it should do with broadcast addresses etc though.

    Some examples:

    >>> dist('192.168.1.254', '192.168.1.240')
    14L
    >>> dist('192.168.1.254', '192.168.2.1')
    65283L
    >>> dist('192.168.1.101', '192.168.56.1')
    3604380L
    >>> dist('192.168.1.101', '172.30.130.66')
    5630092231245859L
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题