Python not getting IP if cable connected after script has started

后端 未结 3 1624
醉酒成梦
醉酒成梦 2021-01-16 14:51

I hope this doesn\'t cross into superuser territory.

So I have an embedded linux, where system processes are naturally quite stripped. I\'m not quite sure which syst

相关标签:
3条回答
  • 2021-01-16 15:27

    Sounds like httplib caches /etc/resolv.conf which is updated after your DHCP client obtains an IP.

    You might consider writing a wrapper script that waits until an IP address is obtained, then calls your python script.

    Alternatively, you could try to, within your python script, not open any socket connections until you have acquired an IP address and /etc/resolv.conf updated.

    Edit

    httplib uses socket.create_connection() which, after some searching, I found does cache /etc/resolv.conf. (Well, it seems that the embedded version of libc is actually doing the caching).

    You could try SugarLabs' solution, although I can't speak to it's effectiveness.

    0 讨论(0)
  • 2021-01-16 15:34

    After alot more research, the glibc problem jedwards suggested, seemed to be the problem. I did not find a solution, but made workaround for my usecase. Considering I only use one URL, I added my own "resolv.file" . A small daemon gets the IP address of the URL when PHY reports cable connected. This IP is saved to "my own resolv.conf". From this file the python script retrieves the IP to use for posts.

    Not really a good solution, but a solution.

    0 讨论(0)
  • 2021-01-16 15:54

    it might be that one of the python modules is caching the state of the network, and so it isn't using the latest settings. Try and reload all the network related modules. A simple example of this is:

    import sys, socket, urllib
    
    for i in [sys, socket, urllib]:
        reload(i)
    

    if that doesn't work look around in sys.modules to see what else got imported, and try more modules there. A more extreme version of the reloading would be the code below, that you could try as a last ditch effort.

    code

    import sys
    print 'reloading %s modules ' % len(sys.modules)
    for name, module in sys.modules.items():
        try:
            reload(module)
        except:
            print 'failed to import %s' % name
    

    output

    reloading 42 modules 
    failed to import __main__
    failed to import encodings.encodings
    failed to import encodings.codecs
    failed to import lazr
    failed to import encodings.__builtin__
    
    0 讨论(0)
提交回复
热议问题