Dan Talayco | e37999f | 2010-02-09 15:27:12 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | """ |
| 4 | Network utilities for the OpenFlow controller |
| 5 | """ |
| 6 | |
| 7 | import socket |
| 8 | |
| 9 | RCV_TIMEOUT_DEFAULT = 10 |
| 10 | HOST_DEFAULT = '' |
| 11 | PORT_DEFAULT = 6633 |
| 12 | RCV_SIZE_DEFAULT = 4096 |
| 13 | |
| 14 | def rcv_data_from_socket(sock, timeout=RCV_TIMEOUT_DEFAULT): |
| 15 | """ |
| 16 | Wait for data on a specified socket. |
| 17 | |
| 18 | Time out in (timeout)seconds. |
| 19 | |
| 20 | @param sock control socket |
| 21 | @param timeout Timeout if data hasn't come in a specified seconds |
| 22 | @return A pair (okay, msg) okay is boolean to indicate a packet was |
| 23 | received. msg is the message if okay is True |
| 24 | |
| 25 | """ |
| 26 | sock.settimeout(RCV_TIMEOUT) |
| 27 | try: |
| 28 | rcvmsg = sock.recv(RCV_SIZE) |
| 29 | return (True, rcvmsg) |
| 30 | except socket.timeout: |
| 31 | return (False, None) |
| 32 | |
| 33 | def open_ctrlsocket(host=HOST_DEFAULT, port=PORT_DEFAULT): |
| 34 | """ Open a socket for a controller connection. |
| 35 | |
| 36 | @param host host IP address |
| 37 | @param port transport port number for the test-controller |
| 38 | @retval s socket |
| 39 | """ |
| 40 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 41 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 42 | s.bind((host, port)) |
| 43 | s.listen(1) |
| 44 | return s |