License Public Domain
Lines 42
Keywords
Socket (3)
Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users
Hide
Siafoo is here to make coding less frustrating and to save you time. Join Siafoo Now or Learn More

Simple example of extending python sockets Atom Feed 1

In Brief A trivial example of creating a socket that acts like a normal socket and a custom socket with a new protocol depending on the given family.... more
# 's
 1#! /usr/bin/python
2
3# This should probably be a * import so that evil_socket can act like the real thing
4from socket import AF_INET, SOCK_STREAM, _socketobject
5AF_EVIL = 1337
6
7class evil_socket(_socketobject):
8
9 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
10
11 self.evil = family == AF_EVIL
12 family = AF_INET if self.evil else family
13
14 _socketobject.__init__(self, family, type, proto, _sock)
15
16 if self.evil:
17 print 'We are Evil!'
18 # Set our recv method since delegation killed it
19 setattr(self, 'recv', getattr(self, 'evil_recv'))
20
21 # This has to be named something other than 'recv' because the
22 # parent socket class, _socketobject, delegates the 'recv' method
23 # to the OS recv class killing our definition, I am not sure
24 # what would be a good way to stop the full delegation and still be
25 # left with a '_socketobject' subtype. Note that unless the base class
26 # init method is called, none of the base class methods can actually be called
27 # on a subclass
28 def evil_recv(self, buffersize, flags = 0):
29 data = self._sock.recv(buffersize, flags)
30 data = list(data)
31 data.reverse()
32 return ''.join(data)
33
34socket = SocketType = evil_socket
35
36if __name__ == '__main__':
37
38 TestAddress = ('127.0.0.1', 22)
39
40 # Non-evil
41 s = socket()
42 s.connect(TestAddress)
43 data = s.recv(100)
44 s.close()
45 print data
46
47 # Evil
48 s = socket(family=AF_EVIL)
49 s.connect(TestAddress)
50 data = s.recv(100)
51 s.close()
52
53 print data

A trivial example of creating a socket that acts like a normal socket and a custom socket with a new protocol depending on the given family.

If you know of a better way to do this let me know.

Warning

You have to have SSH running on your local machine to get this to work, or put another address