3 # wpa_supplicant/hostapd control interface using Python
4 # Copyright (c) 2013, Jouni Malinen <j@w1.fi>
6 # This software may be distributed under the terms of the BSD license.
7 # See README for more details.
17 def __init__(self, path, port=9877):
25 mode = os.stat(path).st_mode
26 if stat.S_ISSOCK(mode):
34 self.s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
36 self.local = "/tmp/wpa_ctrl_" + str(os.getpid()) + '-' + str(counter)
38 self.s.bind(self.local)
40 self.s.connect(self.dest)
48 ai_list = socket.getaddrinfo(path, port, socket.AF_INET,
50 for af, socktype, proto, cn, sockaddr in ai_list:
51 self.sockaddr = sockaddr
53 self.s = socket.socket(af, socktype)
55 self.s.sendto("GET_COOKIE", sockaddr)
56 reply, server = self.s.recvfrom(4096)
60 print "connect exception ", path, str(port)
74 # Need to ignore this allow the socket to be closed
83 def request(self, cmd, timeout=10):
85 self.s.sendto(self.cookie + cmd, self.sockaddr)
88 [r, w, e] = select.select([self.s], [], [], timeout)
90 return self.s.recv(4096)
91 raise Exception("Timeout on waiting response")
96 res = self.request("ATTACH")
100 raise Exception("ATTACH failed")
103 if not self.attached:
105 while self.pending():
107 res = self.request("DETACH")
108 if "FAIL" not in res:
109 self.attached = False
111 raise Exception("DETACH failed")
118 # Need to ignore this to allow the socket to be closed
119 self.attached = False
120 self.request("TERMINATE")
123 def pending(self, timeout=0):
124 [r, w, e] = select.select([self.s], [], [], timeout)
130 res = self.s.recv(4096)