Friday, 26 August 2016

Use Python for Socket Programming to connect two or more PCs to share a text file.

Os: Fedora 20
Network: Switched LAN(Ethernet)

Note: Program fails to work on Local Area Network. Program works flawlessly on localhost.

While this script works perfectly fine on loop back ie on the same machine, it fails on networks.For some unknown reasons I havent' been able to get this script running of a local network consisting of fedora linux machine despite tweaking with the firewall. I don't get much time to work on local networks and am currently busy with some other endeavors. 


Code


Client.py


#!/usr/bin/python           

import socket               # Import socket module
print "Client Side Program"
s = socket.socket()         # Create a socket object
host = raw_input("Enter ip for server:\t") # Get local machine name
port = 40003              # Reserve a port for your service.
s.connect((host, port))
s.send(raw_input("Enter the file path:\t"))
print s.recv(1024)
print s.recv(2048)
s.close                     # Close the socket when done


Server.py


#!/usr/bin/python          

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 40003            # Reserve a port for your service.
s.bind(('127.0.0.1', port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   print 'Client requesting file:\t'
   filename=c.recv(1024)
   print filename
   fd=open(filename,"r")
   data=fd.read()
   fd.close()
   c.send("Begining to send file contents\n"+data+"Thankyou for connecting")
   c.close()                # Close the connection


Output

Server Side Output
[te@dbsl2 asignment 6]$ python server.py
Got connection from ('127.0.0.1', 54553)
Client requesting file:   
/home/te/tes

Client Side Output
[te@dbsl2 asignment 6]$ python client.py
Client Side Program
Enter ip for server:    127.0.0.1
Enter the file path:    /home/te/test
Begining to send file contents
This is the content of test file.
Thankyou for connecting

No comments:

Post a Comment