# 2013-05-21 johnpfeiffer
import socket
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) # ipv4 , TCP (let's skip udp SOCK_DGRAM for now...)
s.connect( ('www.google.com', 80) ) # tuple of host and port
s.send( 'GET / HTTP/1.1\r\n\r\n' ) # basic HTTP get request of the root
website = s.recv( 1000 ) # get 1000 bytes, then the socket self destructs, if s.recv() returns 0 the other side has closed it
print website
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) # ipv4 , TCP (let's skip udp SOCK_DGRAM for now...)
remote_ip = socket.gethostbyname( host )
"""
try:
socket.gethostbyaddr( '8.8.8.8' ) # ('google-public-dns-a.google.com', [], ['8.8.8.8'])
except socket.error as error:
print 'Error code: ' + str( error[0] ) + ' , Error message : ' + error[1]
"""
# echo server that terminates after 3 requests have been handled
import socket
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.bind( ('127.0.0.1', 80) ) # alternatives: 'localhost' or socket.gethostname() , or socket.getfqdn()
s.listen( 1 ) # at most one client at a time, refuse more concurrent connections
max = 3
count = 0
while count < max:
count += 1
(client,addr) = s.accept() # typically use threads, ct = client_thread(clientsocket) \ ct.run()
data = client.recv( 1024 ) # up to 1KB
client.sendall( data )
client.close()
s.close()
# http://docs.python.org/2/howto/sockets.html