import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = raw_input("Enter Server IP: ")
msg = raw_input("Message: ")
s.sendto(msg,(ip,50000))
s.close()
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
try:
s.bind(("",500))
while True:
data,address = s.recvfrom(1024)
print "[%s] %s" % (address[0],data)
finally:
s.close()
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 50000))
s.listen(1)
try:
while True:
connection, address = s.accept()
while True:
data = connection.recv(1024)
if not data:
connection.close()
break
print "[%s] %s" % (address[0], data)
msg = raw_input("Answer: ")
connection.send(msg)
finally:
s.close()
import socket
ip = raw_input("IP-Address: ")
s = socket.socket(socket.AF_INET, socket.SOCKSTREAM)
s.connect((ip, 50000)
try:
while True:
msg = raw_input("Message: ")
s.send(msg)
answer = s.recv(1024)
print "[%s] %s" % (ip,answer)
finally:
s.close()
s.setblocking(0)
socket.getfqdn([name])
Will give you the full domainname of the domain 'name'.socket.gethostbyname(hostname)
Will give you the IPv4 of the host 'hostname' as stringsocket.gethostname()
Will give you your hostname as a string. With 'socket.gethostbyname(socket.gethostname())' you'll get your IP.socket.getservbyport(port)
Will give you the server type of the port 'port'. 'socket.getservbyport(21)' Will print 'ftp'.socket.setdefaulttimeout(timeout)
Will set a timeout for the maximum waiting time (to recieve data for example). 'timeout' is in seconds.With socket.getdefaulttimeout() you'll get your set timeout.s.getpeername()
Will print you the used port and the connected IPs.sendall(msg)
Will try to send the message 'msg' till the whole string is recieved at the other side or an exception is thrown.s.setblocking(flag)
If 'flag' is 0 then the socketis put into the non-blocking mode. Otherwise it's set into the blocking-mode.Then you have about 99999 Ports, but a lot of them are reserved for protocols (for example port 21 for FTP/TCP protocol)There are exactly 65536 ports, but port 0 is unusable, similar in the manner that you will never seen an IP address with the 4th octet set as 0. Also, I'm really sorry, but the Tin Can analogy was terrible.
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
++++[->++++<]> 16
[
-
>++++ 64
>+++++++ 112
>++++++ 96
>+++ 48
<<<<
]
>+. 65 'A'
>++. 114 'r'
>+++++. 101 'e'
----. 97 'a'
--. 95 '_'
>+. 49 '1'
++. 51 '3'
++++[->++++<]>[->++++>+++++++>++++++>+++<<<<]>+.>++.>+++++.----.--.>+.++.
socket.htonl(x)
Converts a 32-bit-number from the host-byte-order into the network-byte-order.socket.ntohl(x)
Converts a 32-bit-number from the network-byte-order into the host-byte-order.socket.htons(x)
Converts a 16-bit-number from the host-byte-order into the network-byte-order.socket.ntohs(x)
Converts a 16-bit-number from the network-byte-order into the host-byte-order.ord('x')
Converts the letter 'x' into a decimal intereger.chr(x)
Converts the decimal intereger 'x' into a letter.def strtoint(textstring):
strg = list(textstring)
dec = []
for i in range(len(strg)):
dec.append(ord(str(strg[i])))
dec = '000'.join(dec)
return dec
def inttostr(intstring):
dec = str.split(intstring[::-1],000) #reverse to split int correctly
dec = str.split(' '.join(dec)[::-1],' ') #reverse int back and make it to a list
strg = []
for i in range(len(dec)):
strg.append(chr(dec[i]))
strg = ''.join(strg)
return strg
import socket
import select
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(("",50000))
server.listens(5)
clients = []
try:
while True:
read,write,oob = select.select([server] + clients,[],[])
for sock in read:
if sock is server:
client,addr = server.accept()
clients.append(client)
print '+++ Connected to &s' % addr[0]
else:
massage = sock.recv(1024)
ip = sock.getpeername()[0]
if message:
print '[%s] %s' % (ip,message)
else:
print '+++ Closed connection to %s' % ip
sock.close()
clients.remove(sock)
finally:
for c in clients:
c.close()
server.close()
The list 'clients' will contain all clients. The following try/finally is to close the connection correctly. In the 'while True' loop we create an select instance. 'select.select' needs 4 lists: The first is a list wich contains all socket to try to recieve messages,the second to write messages,the third to recieve out-of-band data (urgent data) amd the last one to set a timeout to wake up python if nothing happend (empty list = no timeout).import SocketServer
class ChatRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
addr = self.client_Address[0]
print '+++ Connected to %s' % addr
while True:
s = self.request.recv(1024)
if s:
print '[%s] %s' % (addr,s)
else:
print '+++ Closed connection to %s' % addr
break
As you see it's much easier to write an chat programm with this module. First we create the class 'ChatRequestHandler' wich is derived from the basic class 'SocketServer.BaseRequestHandler'. Then we have to define the 'handle' function wich python will use to manage recieving messages.server = SocketServer.ThreadingTCPServer(("",50000),ChatRequestHandler)
server.serve_forever()
With 'SocketServer.ThreadingTCPServer' we create the true server.SocketServer.TCPServer/SocketServer.UDPServer
This classes can only accept one connection at a time.SocketServer.ThreadingTCPServer / SocketServer.ThreadingUDPServer
With this classes you can make an indefinite number of connections because python does threading with them.SocketServer.ForkingTCPServer / SocketServer.ForkerUDPServer
Like the upper one,but here python will handle every connection in a new tasks.socket
Creates a new socket instance.s.fileno()
Prints the file descriptor of the Server-Socket.s.handle_request()
Tells the server to accept and handle only one connection request at a time.s.serve_forever()
Tells the Server to accpet and handle an indefinite number of connections.rh.request
With 'request' you can get info of a client.rh.client_address
Prints the IP and the used port for the connection.rh.handle()
This function manages the sending/recieving of datarh.setup()
This function,if it's used,will be called before 'handle'.It can contain configuration or something elserh.finish()
This function,if it's used, is called after 'handle'.It can contain a 'Goodbye' message or something else.Just suggesting things to write about :) http://ilab.cs.byu.edu/python/threadingmodule.html (http://ilab.cs.byu.edu/python/threadingmodule.html)This is just a chat application like the upper ones.Does not really more,just looks a bit more complex and is created as a class.
import ftplib
ftp = ftplib.FTP('ftp://ftp.example.com')
ftp.login('myusername','mypass')
ftp.sendcmd('command')
ftp.retrbinary('RETR file',function)
def f(data):
file = ''
file += data
return file
pic = ftp.retrbinary('RETR picture.jpg',f)
ftp.retrlines('RETR file',function)
ftp.storbinary('STOR file',function)
ftp.storlines('STOR file',f)
ftp.rename('oldname','newname')
ftp.delete('file')
ftp.cwd('directory')
ftp.mkd('directory')
ftp.pwd()
ftp.rnd('folder')
ftp.quit()
import smtplib
smtp = smtplib.SMTP('smtp.example.com')
First we import the smtp module,then we connect to a smtp-server (btw,the address doesn't always start with the protocol name,because sometimes the server has an other name (e.g. 'mail.example.com').smtp.login('myusername','mypass')
smtp.sendmail('from','to','message'[,mailoptions,rctpoptions])
smtp.sendmail('mymail@mail.com','friendsmail@othermail.com','Hello World')
Or with more receiver:smtp.sendmail('mymail@mail.com',['firendsmail@othermail.com','fiend2smail@example.com'],'Hellow World')
smtp.quit()