# An example script to connect to Google using socket
import socket
import sys
try:
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
except [Link] as err:
print "socket creation failed with error %s" %(err)
# default port for socket
port = 80
try:
host_ip = [Link]('[Link]')
except [Link]:
# this means could not resolve the host
print "there was an error resolving the host"
[Link]()
# connecting to the server
[Link]((host_ip, port))
print "the socket has successfully connected to google \
on port == %s" %(host_ip)
output:
Socket successfully created
the socket has successfully connected to google
on port == [Link]
Server :
# first of all import the socket library
import socket
# next create a socket object
s = [Link]()
print "Socket successfully created"
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
[Link](('', port))
print "socket binded to %s" %(port)
# put the socket into listening mode
[Link](5)
print "socket is listening"
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = [Link]()
print 'Got connection from', addr
# send a thank you message to the client.
[Link]('Thank you for connecting')
# Close the connection with the client
[Link]()
client:
# start the server
$ python [Link]
$ telnet localhost 12345
Output :
# in the [Link] terminal you will see
# this output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('[Link]', 52617)
# In the telnet terminal you will get this:
Trying ::1...
Trying [Link]...
Connected to localhost.
Escape character is '^]'.
Thank you for connectingConnection closed by foreign host.
# Import socket module
import socket
# Create a socket object
s = [Link]()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
[Link](('[Link]', port))
# receive data from the server
print [Link](1024)
# close the connection
[Link]()
# start the server:
$ python [Link]
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('[Link]', 52617)
# start the client:
$ python [Link]
Thank you for connecting