You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.3 KiB
89 lines
2.3 KiB
# -*- coding: utf-8 -*-
|
|
import select
|
|
import socket
|
|
import threading
|
|
import random
|
|
import config
|
|
from Queue import Queue, Empty
|
|
|
|
MAGIC_PACKET = ""
|
|
for i in xrange(50):
|
|
MAGIC_PACKET += chr(random.randrange(ord('a'),ord('z')))
|
|
|
|
|
|
|
|
def split_args(txt):
|
|
SA_S0, SA_QUOT = range(2)
|
|
split_args_state = SA_S0
|
|
# FSM:
|
|
#
|
|
# else
|
|
# ,--.
|
|
# | V "
|
|
# `-(S0)----->(QUOT)
|
|
# ^ |
|
|
# `---------´
|
|
# "
|
|
#
|
|
args = []
|
|
current = u""
|
|
for i in xrange(len(txt)):
|
|
c = txt[i]
|
|
if split_args_state==SA_S0:
|
|
if c=='"':
|
|
split_args_state = SA_QUOT
|
|
if len(current)!=0:
|
|
args.append(current)
|
|
current = u""
|
|
elif c in " \t\n":
|
|
if len(current)!=0:
|
|
args.append(current)
|
|
current = u""
|
|
else:
|
|
current += c
|
|
elif split_args_state==SA_QUOT:
|
|
if c=='"':
|
|
split_args_state = SA_S0
|
|
else:
|
|
current += c
|
|
else:
|
|
assert False
|
|
if len(current)!=0:
|
|
args.append(current)
|
|
return args
|
|
|
|
|
|
def get_local_ip():
|
|
def udp_listening_server():
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
s.bind(('<broadcast>', 8888))
|
|
s.setblocking(0)
|
|
while True:
|
|
result = select.select([s],[],[],10)
|
|
if len(result[0])==0 :
|
|
print "Warning using default local ip"
|
|
queue.put([config.LOCAL_IP])
|
|
break
|
|
|
|
msg, address = result[0][0].recvfrom(1024)
|
|
msg = unicode(msg)
|
|
if msg == MAGIC_PACKET:
|
|
queue.put(address)
|
|
break
|
|
|
|
queue = Queue()
|
|
thread = threading.Thread(target=udp_listening_server)
|
|
thread.queue = queue
|
|
thread.start()
|
|
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
s2.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
waiting = True
|
|
while waiting:
|
|
s2.sendto(bytes(MAGIC_PACKET), ('<broadcast>', 8888))
|
|
try:
|
|
address = queue.get_nowait()
|
|
except Empty:
|
|
pass
|
|
else:
|
|
waiting = False
|
|
return address[0]
|
|
|