UDP broadcast and automatic server discovery in python, TCP socket unavailable -


i'm developing reverse shell application in python, , right i'm trying implement autodiscovery feature. should work follows:

  1. the server broadcasts ip/port listens connections on, , waits client. if no client tries connect in few seconds, broadcasts again (and repeat till connection).
  2. the client tries receive broadcast of server, , connects advertised ip/port.

the broadcast works fine, client receives ip/port , connects, after using connected pair of ports (server side):

socket.error: [errno 35] resource temporarily unavailable

server side test code:

sckt = socket.socket(socket.af_inet, socket.sock_stream) sckt.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1) sckt.settimeout(2) sckt.bind(('', 9999)) sckt.listen(5)  broadcastsocket = socket.socket(socket.af_inet, socket.sock_dgram) broadcastsocket.setsockopt(socket.sol_socket, socket.so_broadcast, 1) broadcastsocket.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1) while true:     broadcastsocket.sendto(socket.gethostbyname(socket.getfqdn()) + ' ' + str(9999), ('<broadcast>', 8888))     try:         sock, address = sckt.accept()         break     except socket.timeout:         pass broadcastsocket.close() sckt.settimeout(none)  sock.send('test') # if add time.sleep(1) here, works, don't why # sock unavailable @ first, available second later print sock.recv(1) # fails # note fails recv buffer size, instance 1024 

why on earth want receive 1 byte of data, might ask. have algorithm prefixes messages lengths, , receiver reads prefix byte-by-byte till delimiter, thats why. client side test code:

broadcastsocket = socket.socket(socket.af_inet, socket.sock_dgram) broadcastsocket.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1) broadcastsocket.settimeout(3) broadcastsocket.bind(('', 8888)) while true:     try:         data = broadcastsocket.recv(1024)         break     except socket.timeout:         pass broadcastsocket.close()  sckt = socket.socket(socket.af_inet, socket.sock_stream) sckt.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1) sckt.connect((str(data.split()[0]), int(data.split()[1])))  print sckt.recv(1024) sckt.send('lel') 

if omit whole broadcast , autodiscovery part of code , manually enter ip/port of server print sock.recv(1) doesn't fail. clues on issue might be?

change sckt.settimeout(none) sock.settimout(none) in server code.

you want have accepted socket in blocking mode , not accepting one.

this ensures sckt.recv waits incoming message client.

p.s. sock.setblocking(1) same


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -