CN EXPT 5-1
CN EXPT 5-1
PRACTICAL 5
AIM : To study and Implement Socket Programming using PYTHON.
1. TCP Client, TCP Server
CODE:
Program 1.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
import socket
ip = socket.gethostbyname('www.google.com')
print(ip)
Output:
Program 2.
# An example script to connect to Google using socket programming in
Python
import socket # for socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except socket.error as err:
print ("socket creation failed with error %s" %(err))
try:
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
# this means could not resolve the host
print ("there was an error resolving the host")
sys.exit()
Output:
Program 3.
# first of all import the socket library
import socket
# send a thank you message to the client. encoding to send byte type.
c.send('Thank you for connecting'.encode())
Output:
Program 4.
# Import socket module
import socket
# receive data from the server and decoding to get the string.
print (s.recv(1024).decode())
# close the connection
s.close()
CONCLUSION: Therefore, we have successfully implemented socket programming using
python and understood how to successfully create sockets.