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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题