The project demonstrate Network Programming in Python by doing Socket Programming. The project have two parts: SERVER PROGRAM (server.py) and CLIENT PROGRAM (client.py).
Server program is executed first and it waits for clients to get connected. When a client connects it show IP address and port number of client. The server program authenticate the user name and password which is inputted in the client program, by reading users.txt file which stores records of users. If the user name and password is available, then authentication is successful, and it sends the message “Login is successful” to the client where this message is displayed. And if authentication fails, it displays the message “Username not available” if the inputted user name is not available in the user.txt file or “User already logged in” if the user is already logged to the server. When login is successful, the server stores the username and password to the logged users list.
Server code for Login:
Client code for Login :
After login is successful, client program displays a menu with six options :
In option 1, we input organization name in the client program. It is then sent to server program. In server program, it calls a function in which it loops through list of organization records and checks if the organization name is there in the record. If the organization name exists, it retrieve domain name and IP address of that organization and sent back to client program. If the organization name is not present in organization list, it send back error message “Organization name is unknown”, which is displayed in client program.
The server and client part of coding for option 1 :
Server code :
Client code :
In option 2, Server program executes methods calcMin(), calcMax() and calcMean() to calculate and find minimum, maximum and mean value of the minutes from organization records list and send these three values to client program where they are printed on the screen.
The server and client code for this option 2 :
In option 3, organization list is sorted either in ascending order of organization name or in descending order of time in minutes.
The server and client code for option 3 :
In option 4, we stores record of new organization in the organization.txt file. First we input organization name, domain name, IP address and time in minutes in the client program. Then this information is sent to server program. Server program, checks whether the organization name is present in the current organization list. If organization name is not present in the organization list, then this new record is added to the organization list and this new record is updated in the organization.txt file and message is send to client program “Organization data saved successfully” and if the organization name is present in organization list, it displays the error message “Organization already exists”. The user is able to enter the new organization record for 3 times and after that the program terminates if the existing organization name is entered 3 times.
The server and client code for this option 4 :
In option 5, we delete record of organization from the organizations.txt file. We input name of the organization name in the client program. Organization name is send to server program, and checks if organization name is present in organization list. If organization name is present, it deletes organization record from the list and update organizations.txt file. If organization name is not present in the organization list, server program send error message “Organization does not exists” which is printed in the client program.
The server and client code for option 5 :The option 6 is used to exit program by displaying a message
Program Coding and Output Screens :
SERVER PROGRAM CODING :
import socket # import socket library
import sys
loggedUser = [] # logged user list
users = [] # users list
orgLst = [] # organization records list
dom = ”
ipadr = ”
q = 0
def getKeyName(dlist):
return dlist[0]
def getKeySize(dlist):
return dlist[3]
def calcMin(): # function to find minimum of minutes
minminu = []
for o in orgLst: # iterate organization list
flds = o.strip().split(‘ ‘) # break record at blank spaces
minminu.append(int(flds[3])) # store minutes in minminu list
mindat = minminu[0] # get minutes at index 0
for x in range(0, len(minminu)): # iterate minminu list
if minminu[x] < mindat: # if current minminu value < mindata
mindat = minminu[x] # store current value to mindata
return str(mindat) # return mindat value
def calcMax(): # function to find the maximum of the minutes
maxminu = []
for o in orgLst: # iterate organization list
flds = o.strip().split(‘ ‘) # break record at blank spaces
maxminu.append(int(flds[3])) # store minutes in maxminu list
maxdat = maxminu[0] # store minutes at index 0
for x in range(0, len(maxminu)): # iterate maxminut list
if maxminu[x] > maxdat: # if the current value > maxdata
maxdat = maxminu[x] # store the current value to maxdata
return str(maxdat) # return maxdat value
def calcMean(): # function to find mean of minutes
meanminu = []
for o in orgLst: # iterate organization list
flds = o.strip().split(‘ ‘) # break record at blank spaces
meanminu.append(int(flds[3])) # store minutes in meanminu list
sum1 = 0 # initialize sum to 0
for x in range(0, len(meanminu)): # iterate meanminu list
sum1 = sum1 + meanminu[x] # add minutes to sum variable
mean = int(sum1 / len(meanminu)) # find mean value
return str(mean) # return mean value
def loadOrg(): # funtion to load organization record to orgLst
fread = open(‘organisations.txt’, ‘r’) # open file for reading
lines = fread.readlines() # read all records from file
for l in lines: # iterate through all the lines
orgLst.append(l) # store organization record to orgLst
fread.close() # close the file
def findDomainIp(orgnam): # function to find the domain name and ip address
q = 0
for o in orgLst: # iterate organisation list
if orgnam in o: # if orgnam is present in current organisation record
flds = o.strip().split(‘ ‘) #break record at blank spaces
global dom
global ipadr
dom = flds[1] # store domain name
ipadr = flds[2] # store ip address
q = 1
break
return q
def findLoggedUser(usrnam, pwd): # funtion to find whether user is logged in
found = False
for usr in loggedUser: # iterate logged user list
if usrnam + ‘ ‘ + pwd in usr: # if username and password is present in current record
found = True # set found = true
break
return found # return found value
def login(usrnam, pswd): # funtion to login the user
fread1 = open(‘users.txt’, ‘r’) # open users.txt file for reading
users = fread1.readlines() # read records of users and store to users list
found = False
mssg = ”
for usr in users: # iterate users list
status = findLoggedUser(usrnam, pswd) # call findLoggedUser method
if status == True: # status is true, means user is already logged in
found = True
mssg = ‘User already logged in’
break
else:
if usrnam + ‘ ‘ + pswd in usr: # if username and password present in users list
loggedUser.append(usr) # add user to the logged user list
found = True
mssg = ‘Login is successfull’ # store message that login is success
break
if found == False:
mssg = ‘Username not available’ # store message username not available
fread1.close() # close the file
return mssg
def main():
loadOrg() # call loadOrg function and load organization record to orgLst
try:
ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # make server socket
except socket.error: # call the exception if socket creation fails
print(‘socket creation failed’)
sys.exit()
shostname = socket.gethostname() # store local machine name
sport = 7777 # port of the server from where it get the client connection
ssocket.bind((shostname, sport)) # bind host name and port
ssocket.listen(5) # set socket for multiple connections
clsocket, address = ssocket.accept() # set server socket to receive the connection from client
print(‘Connected from %s’ % (str(address))) # print client ip address and port number
while True:
usrname = clsocket.recv(1024).decode(‘ascii’) # receive username and password from client
paswd = clsocket.recv(1024).decode(‘ascii’)
status = login(usrname, paswd) # call login function
clsocket.send(status.encode(‘ascii’)) # send status of login to client
break
while True:
choice = clsocket.recv(1024).decode(‘ascii’) # receive choice selected from menu in client program
clsocket.send(choice.encode(‘ascii’)) # send choice to client for acknowledgement
if choice == ‘1’:
organame = clsocket.recv(1024).decode(‘ascii’) # receive the organization name from client
status = findDomainIp(organame) # call findDomainIp function
if status == 1: # if status = 1, domain name and IP address is available
global dom
global ipadr
dataout = dom + ‘ ‘ + ipadr + ‘n’ # store the domain and ip value
clsocket.send(dataout.encode(‘ascii’)) # send data to client
else:
clsocket.send(‘Organisation is unknown’.encode(‘ascii’)) # send organization is unknown to client
continue
elif choice == ‘2’:
minval = calcMin() # call calcMin() function to find minimum of minutes
maxval = calcMax() # call calcMax() function to find maximum of minutes
meanval = calcMean() # call calcMean() function to find mean of minutes
# send minval, maxval and meanval to client
clsocket.send(minval.encode(‘ascii’))
clsocket.send(maxval.encode(‘ascii’))
clsocket.send(meanval.encode(‘ascii’))
continue
elif choice == ‘3’:
ch = clsocket.recv(1024).decode(‘ascii’) # receive sorting choice
dataout = ”
if ch == ‘1’: # sort organisation list in ascending order of organization name
orgLst.sort(reverse=False, key=getKeyName) # sort organisation list
for o in orgLst:
flds = o.strip().split(‘ ‘)
dataout = dataout + flds[0] + ‘ ‘ + flds[1] + ‘ ‘ + flds[2] + ‘ ‘ + flds[3] + ‘n’
elif ch == ‘2’: # sort the organisation list in descending order of minutes
sortlst = []
for o in orgLst:
flds = o.strip().split(‘ ‘)
dataout = flds[0] + ‘,’ + flds[1] + ‘,’ + flds[2] + ‘,’ + flds[3] + ‘n’
sortlst.append(dataout)
dataout = ”
sortlst.sort(reverse=True, key=getKeySize) # sort organization list
for o1 in sortlst:
flds = o1.strip().split(‘,’)
dataout = dataout + flds[0] + ‘ ‘ + flds[1] + ‘ ‘ + flds[2] + ‘ ‘ + flds[3] + ‘n’
clsocket.send(dataout.encode(‘ascii’)) # send sorted list to client
continue
elif choice == ‘4’:
# receive values of new organization name, domain name, ip address and minutes from client
onam = clsocket.recv(1024).decode(‘ascii’)
dnam = clsocket.recv(1024).decode(‘ascii’)
iaddr = clsocket.recv(1024).decode(‘ascii’)
minut = clsocket.recv(1024).decode(‘ascii’)
found = False
status = False
for o in orgLst: # iterate the orgLst
if onam in o: # if new organisation name present in orgLst
found = True
break
if found == False: # New organisation name not present in orgLst, add new record to orgLst
datain = onam + ‘ ‘ + dnam + ‘ ‘ + iaddr + ‘ ‘ + minut + ‘n’
orgLst.append(datain)
fw = open(‘organisations.txt’, ‘w’) # append organizations.txt file with new organization record
for o in orgLst:
flds = o.strip().split(‘ ‘)
fw.writelines(‘%s %s %s %sn’ % (flds[0], flds[1], flds[2], flds[3])) # write record to file
fw.close() # close file
status = ‘True’
else:
status = ‘False’
clsocket.send(status.encode(‘ascii’)) # send status to client
continue
elif choice == ‘5’:
onam = clsocket.recv(1024).decode(‘ascii’) # receive organizaion name from client
found = False
for o in orgLst: # iterate orgLst and find if orgnasation name present in orgLst
if onam in o: # if organization name is present, deleteremove it
orgLst.remove(o) # delete organzation record from orgLst
found = True
break
if found == False:
status = ‘False’
else:
status = ‘True’
fw1 = open(‘organisations.txt’, ‘w’) # open organisations.txt file for updation
for o in orgLst:
flds = o.strip().split(‘ ‘)
fw1.writelines(‘%s %s %s %sn’ % (flds[0], flds[1], flds[2], flds[3])) #write record to file
fw1.close()
clsocket.send(status.encode(‘ascii’)) # send status to client
continue
elif choice == ‘6’:
print(‘Have a nice day ! Program Ended’)
break
ssocket.close() # close the server socket
main() # call the main() function
import socket # import socket library
import sys
def main():
clsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # make client socket
clhostname = socket.gethostname() # retreive host name of local machine
clport = 7777 # set client port to connect
clsocket.connect((clhostname,clport)) # connect client to server
c = 0
while c < 3:
usrname = input(‘Input user name : ‘) # input user name and password
paswrd = input(‘Input password : ‘)
clsocket.send(usrname.encode(‘ascii’)) # send username and password to server
clsocket.send(paswrd.encode(‘ascii’))
mssg = clsocket.recv(1024).decode(‘ascii’) # get message from server
c = c + 1
if mssg == ‘Logged in successfully’:
break
else:
if c < 3:
print(mssg) # login failed print error message
continue
else:
sys.exit(0)
print(mssg) # display the success login message
while True:
# Print menu options
print(‘——————————‘)
print(‘ MENU ‘)
print(‘——————————‘)
print()
print(‘1. Get Domain Name and IP’)
print(‘2. Get Statistics’)
print(‘3. Sort Data’)
print(‘4. Add Organisation’)
print(‘5. Remove Organisation’)
print(‘6. Quit’)
cho = input(‘Input choice (1,2,3,4,5, or 6) : ‘) # input user choice
clsocket.send(cho.encode(‘ascii’)) # send choice to server for acknowledgement
mssg = clsocket.recv(1024).decode(‘ascii’) # receive the acknowlegment from server
print(‘Choice %s selected ‘ % (str(mssg))) # print message from server
if cho == ‘1’:
orgnam = input(‘Input organisation name : ‘) # input organisation name
clsocket.send(orgnam.encode(‘ascii’)) # send organisation name to server
datain = clsocket.recv(1024).decode(‘ascii’) # receive data from server
if datain != ‘Organisation is unknown’:
rdata = datain.strip().split(‘ ‘)
# print domain name and ip address
print(‘Domain Name : %s ‘ % (rdata[0]))
print(‘IP Address : %s ‘ % (rdata[1]))
else:
print(datain) # print error message from server
continue
elif cho == ‘2’:
# get minimum, maximum and mean value from server
mnvalue = clsocket.recv(1024).decode(‘ascii’)
mxvalue = clsocket.recv(1024).decode(‘ascii’)
mevalue = clsocket.recv(1024).decode(‘ascii’)
#print values of minimum, maximum and mean of minutes
print(‘Minimum number of minutes : %s’ % (mnvalue))
print(‘Maximum number of minutes : %s’ % (mxvalue))
print(‘Mean number of minutes : %s’ % (mevalue))
continue
elif cho == ‘3’:
c = 0
while True:
ch = input(‘1. sort by name, 2 sort by size : ‘) # input sorting choice
if ch == ‘1’ or ch == ‘2’ :
clsocket.send(ch.encode(‘ascii’)) # send choice to server
break
else:
c = c + 1 # enter the choice for 3 times
if c == 3:
sys.exit(0) # exit after 3 unsuccessful attempts
else:
continue
datain = clsocket.recv(1024).decode(‘ascii’) # receive sorted data from server
print(datain) # print sorted data
continue
elif cho == ‘4’:
c = 0
while True:
# input organization name, domain name, ip address and minutes
orgnam = input(‘Input Organisation name : ‘)
domnam = input(‘Input Domain Name : ‘)
ipaddr = input(‘Input IP Address : ‘)
minute = input(‘Input minutes : ‘)
# send inputted values to server
clsocket.send(orgnam.encode(‘ascii’))
clsocket.send(domnam.encode(‘ascii’))
clsocket.send(ipaddr.encode(‘ascii’))
clsocket.send(minute.encode(‘ascii’))
# get status from server
stat = clsocket.recv(1024).decode(‘ascii’)
c = c + 1
if stat == ‘True’: # if status = true, record saved successfully
print(‘Organisation data saved successfully’)
break
else: # else organization name exists
print(‘Organisation already exists’)
if c <= 3:
continue
else:
sys.exit(0)
break
continue
elif cho == ‘5’:
c = 0
while True:
orgnam = input(‘Input Organisation Name : ‘) # input organisation name
clsocket.send(orgnam.encode(‘ascii’)) # send oranisation name to server
stat = clsocket.recv(1024).decode(‘ascii’) # get status from server
c = c + 1
if stat == ‘False’: # if status = false, organisation does not exist
print(‘Organisation does not exist’)
if c <= 3:
continue
else:
sys.exit(0)
break
else:
print(‘Organisation record removed successfully’)
break
continue
elif cho == ‘6’: # exit program
print(‘Program ended !!’)
break
clsocket.close() # close the client socket
main()
Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]
Type “copyright”, “credits” or “license” for more information.
IPython 5.3.0 — An enhanced Interactive Python.
? -> Introduction and overview of IPython’s features.
%quickref -> Quick reference.
help -> Python’s own help system.
object? -> Details about ‘object’, use ‘object??’ for extra details.
Input user name : kar
Input password : 3456
Logged in successfully
Get Domain Name and IP
Input choice (1,2,3,4,5, or 6) : 3
Choice 3 selected
Organic www.organic.org 115.130.100.20 8765
Ptu www.ptu.edu.in 123.56.3.100 6789
Picaxi www.picaxi.com 100.125.200.45 3467
Regania www.regania.com 235.125.100.5 2345
Spectron www.spectron.co.uk 195.100.45.2 8765
Woodbond www.woodbond.co.au 107.125.20.12 7654
Input choice (1,2,3,4,5, or 6) : 2
Choice 2 selected
Minimum number of minutes : 2345
Maximum number of minutes : 9876
Mean number of minutes : 6935
Input choice (1,2,3,4,5, or 6) : 1
Input organisation name : abc
Organisation is unknown
Input organisation name : Organic
Domain Name : www.organic.org
IP Address : 115.130.100.20
Get Domain Name and IP
Choice 4 selected
Input Organisation name : Connect
Input Domain Name : www.connect.com
Input IP Address : 110.205.100.20
Input minutes : 6700
Organisation data saved successfully
Choice 5 selected
Input Organisation Name : kkkk
Organisation does not exist
Input Organisation Name : Connect
Organisation record removed successfully
Essay Writing Service Features
Our Experience
No matter how complex your assignment is, we can find the right professional for your specific task. Contact Essay is an essay writing company that hires only the smartest minds to help you with your projects. Our expertise allows us to provide students with high-quality academic writing, editing & proofreading services.Free Features
Free revision policy
$10Free bibliography & reference
$8Free title page
$8Free formatting
$8How Our Essay Writing Service Works
First, you will need to complete an order form. It's not difficult but, in case there is anything you find not to be clear, you may always call us so that we can guide you through it. On the order form, you will need to include some basic information concerning your order: subject, topic, number of pages, etc. We also encourage our clients to upload any relevant information or sources that will help.
Complete the order formOnce we have all the information and instructions that we need, we select the most suitable writer for your assignment. While everything seems to be clear, the writer, who has complete knowledge of the subject, may need clarification from you. It is at that point that you would receive a call or email from us.
Writer’s assignmentAs soon as the writer has finished, it will be delivered both to the website and to your email address so that you will not miss it. If your deadline is close at hand, we will place a call to you to make sure that you receive the paper on time.
Completing the order and download