Python, wait until the network interface closes?

I have a python script that opens a port and listens for it on raspberries. I added it to /etc/rc.local and everything works correctly. But my problem is the socket, which is not created during the execution of the process.

s = socket.socket()      
s.bind((host_ip,port)) #e.g. host_ip='192.168.1.32' , port=12345
s.listen(5)
while True:
    c,addr = s.accept()
    c.send('ACK')
    c.close()

the above code does not execute because the connection 'eth0' is not available. What should I do? Should I check the status of the socket until the connection is available? Is there an even more complicated solution?

+4
source share
3 answers

Like this:

import urllib2,thread
from time import sleep
import netifaces


class _check:
    def __init__(self):
        self.uri="http://www.google.com"
        self.period = 5
        self.status = False
        self.ifaces()
    def check(self):
        try:
            answ = urllib2.urlopen(self.uri)
            if answ:
                self.status = True
                #Now can run your awesome code !
                print "okay go take a beer"
        except Exception,e : print e

    def timer(self,pass_arg) :
        while True :
            if   self.status != True :
                self.check()
                sleep(self.period)
                print "running"
            elif   self.status == True :
                print "thread ending"
                break
    def ifaces(self):
        for i in netifaces.interfaces() :
            try:
                print i,netifaces.ifaddresses(i)[2]
            except:
                print i, "iface not up !"


check = _check()
thread.start_new_thread(check.timer,(None,))

so that this answer matches my comment.

+2
source

accept() - , , , , accept() .

0

Python, , , .

  • When you listen, you do not need host ( s.bind(('',port))).

  • You need to define a function or event handler that occurs when the connection is established (possibly handle_connectin Python).

  • In the handler function, you connect the client to a port other than the port you are currently listening to.

0
source

Source: https://habr.com/ru/post/1626130/


All Articles