- Mastering Python for Networking and Security
- José Manuel Ortega
- 190字
- 2021-07-16 17:40:06
Basic client with the socket module
In this example, we are testing how to send and receive data from a website.Once the connection is established, we can send and receive data. Communication with the socket can be done very easily thanks to two functions, send () and recv (), used for TCP communications. For UDP communication, we use sendto (), and recvfrom ()
In this socket_data.py script, we create a socket object with the AF_INET and SOCK_STREAM parameters. We then connect the client to the remote host and send it some data. The last step is to receive some data back and print out the response. We use an infinite loop (while True) and we check whether the data variable is empty. If this condition occurs, we finish the loop.
You can find the following code in the socket_data.py file:
import socket
print 'creating socket ...'
# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'socket created'
print "connection with remote host"
s.connect(('www.google.com',80))
print 'connection ok'
s.send( 'GET /index.html HTML/1.1\r\n\r\n')
while 1:
data=s.recv(128)
print data
if data== "":
break
print 'closing the socket'
s.close()