Skip to content

Commit

Permalink
adding ECE files
Browse files Browse the repository at this point in the history
  • Loading branch information
shaohaolin committed Jan 12, 2015
0 parents commit cbb7c73
Show file tree
Hide file tree
Showing 11 changed files with 483 additions and 0 deletions.
104 changes: 104 additions & 0 deletions HTTP Web Proxy Server/proxyServer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@

from socket import *
import sys


# Create a server socket, bind it to a port and start listening
tcpSerPort = 8888
tcpSerSock = socket(AF_INET, SOCK_STREAM) #SOCK_STREAM indicates TCP socket

#bind the server socket and start listening
tcpSerSock.bind(('127.0.0.1', 8888))
tcpSerSock.listen(5)

# fill in start
#fill in ends

while 1:
# Start receiving data from the client
print( 'Ready to serve...')
tcpCliSock, addr = tcpSerSock.accept()
print ('Received a connection from:', addr)
message = tcpCliSock.recv(2048)
if str( message, encoding='utf8' ) != '':
print (message)

# Extract the filename from the given message
print (message.split()[1])
file1 = str( message, encoding='utf8' )
filename = file1.split()[1].split("/")[1]
print (filename)
fileExist = "false"
filetouse = "/" + filename
print (filetouse)
try:
# Check whether the file exist in the cache
f = open(filetouse[1:], "rb")
outputdata = f.readlines()
fileExist = "true"

# ProxyServer finds a cache hit and generates a response message

tcpCliSock.send(bytes("HTTP/1.0 200 OK\r\n",'utf-8'))
tcpCliSock.send(bytes("Content-Type:text/html\r\n",'utf-8'))
# Fill in start.
for i in range(0, len(outputdata)):
tcpCliSock.send(outputdata[i])
# Fill in end.
f.close()
print ('Read from cache')

# Error handling for file not found in cache
except IOError:
if fileExist == "false":
# Create a socket on the proxy server
c = socket(AF_INET, SOCK_STREAM)
hostn = filename.replace("www.", "", 1)
print (hostn)
try:
# Connect to the socket to port 80
c.connect((hostn,80))
print('Socket connected to port 80 of the host')
# fill in start

#fill in ends

# Create a temporary file on this socket and ask port 80 for the file requested by the client
fileobj = c.makefile('rwb')
string1 = "GET " + "http://" + filename + " HTTP/1.0\n\n"
naming = bytes(string1,'utf-8')
c.send(naming)
fileobj.write(naming)

# Read the response into buffer
buff = fileobj.readlines() # read all the files to the buffer



# Create a new file in the cache for the requested file.
# Also send the response in the buffer to client socket and the corresponding file in the cache
tmpFile = open("./" + filename,"wb")
for i in range(0, len(buff)):
tmpFile.write(buff[i])
tcpCliSock.send(buff[i])
# Fill in start.

# Fill in end.

tmpFile.close()
except:
print ("Illegal request")
else:
# HTTP response message for file not found

# Fill in start.
print("File not Found")
# Fill in end.

# Close the client and the server sockets
tcpCliSock.close()

# Fill in start.
tcpSerSock.close()
# Fill in end.

27 changes: 27 additions & 0 deletions Multicasting/multicastingclient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'''
Created on 2014年11月15日
@author: kurt
'''
import socket
import time
Any = '0.0.0.0'
multicast_addr = '224.168.2.9'
multicast_port = 1600

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((Any,multicast_port))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
status = sock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,socket.inet_aton(multicast_addr)+socket.inet_aton(Any))

sock.setblocking(0)
ts=time.time()
while 1:
try:
data,addr = sock.recvfrom(1024)
except socket.error:
pass
else:
print("Client 1 : Data Received from:", addr)
print("and the Received Data is: ",data)
27 changes: 27 additions & 0 deletions Multicasting/multicastingclient2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'''
Created on 2014年11月16日
@author: kurt
'''
import socket
import time
Any = '0.0.0.0'
multicast_addr = '224.168.2.9'
multicast_port = 1600

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((Any,multicast_port))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
status = sock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,socket.inet_aton(multicast_addr)+socket.inet_aton(Any))

sock.setblocking(0)
ts=time.time()
while 1:
try:
data,addr = sock.recvfrom(1024)
except socket.error:
pass
else:
print("Client 2 : Data Received from:", addr)
print("and the Received Data is: ",data)
22 changes: 22 additions & 0 deletions Multicasting/multicastingserver2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'''
Created on 2014年11月16日
@author: kurt
'''
import socket
import time

Any = '0.0.0.0'
sendPort = 1502
multicast_addr = '224.168.2.9'
multicast_port = 1600

msg = "Multicasting Assignment ECE 4436 from Serve 2"

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
sock.bind((Any,sendPort))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
while 1:
time.sleep(4)
sock.sendto(msg.encode(encoding='utf_8'),(multicast_addr,multicast_port))
print('Server 2: multicast packet is sent now')
21 changes: 21 additions & 0 deletions Multicasting/multicastserver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'''
Created on 2014年11月15日
@author: kurt
'''
import socket
import time

Any = '0.0.0.0'
sendPort = 1501
multicast_addr = '224.168.2.9'
multicast_port = 1600

msg = "Multicasting Assignment ECE 4436 from Serve 1"
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
sock.bind((Any,sendPort))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
while 1:
time.sleep(3)
sock.sendto(msg.encode(encoding='utf_8'),(multicast_addr,multicast_port))
print('Server 1 : multicast packet is sent now')
28 changes: 28 additions & 0 deletions NTP/NtpClient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import socket
import struct
import sys
import time
NTP_SERVER = 'pool.ntp.org'
TIME1970 = 2208988800

def sntp_client():
port = 123
buf = 1024
address = (NTP_SERVER,port)
data = '\x1b' + 47 * '\0'

# connect to server
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

client.sendto(data.encode('utf-8'),address)
data, address = client.recvfrom(buf)


if data:
print ('Response received from:', address)

t = struct.unpack( '!12I', data )[10]
t -= TIME1970
print ('\tTime=%s' % time.ctime(t))
if __name__ == '__main__':
sntp_client()
107 changes: 107 additions & 0 deletions SMTP MailClient/emailclient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
from socket import *
import ssl
import base64

# Setup messages

msg = "\r\n Ryan, I am so hungry.Shiiiit." # email body
endmsg = "\r\n.\r\n" # end of body

# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = "smtp.gmail.com"# fill in start # fill in end
port = 587

clientSocket=socket(AF_INET,SOCK_STREAM) #establish a TCP connection with mailserver
clientSocket.connect((mailserver,port))

#Read server response
recv = clientSocket.recv(1024)
print (recv)
if recv[:3] != "220":
print ('220 reply not received from server.')

heloCommand = "HELO Alice\r\n"
clientSocket.send(bytes(heloCommand,'utf-8'))
recv1 = clientSocket.recv(1024)
print (recv1),
if recv1[:3] != '250':
print ('250 reply not received from server.')

# Send STARTTLS command to server and print server response
command = "STARTTLS\r\n"
clientSocket.send(bytes(command, 'utf-8'))

recv1 = clientSocket.recv(1024)
print (recv1)
if recv[:3] != '220':
print ('220 reply not received from server.')

#Wrap the socket with SSL wrapper
tls_clientSocket = ssl.wrap_socket(clientSocket)

# Send HELO command and print server response.
heloCommand = 'HELO Alice\r\n'
tls_clientSocket.send(bytes(heloCommand,'utf-8'))
recv1 = tls_clientSocket.recv(1024)
print (recv1),
if recv1[:3] != '250':
print ('250 reply not received from server.')

# SEND AUTH LOGIN command and Base64 encoded username
command = "AUTH LOGIN \r\n"
tls_clientSocket.send(bytes(command,'utf-8'))

recv1 = tls_clientSocket.recv(1024)
print (recv1)

#Authenticate with User/Password and print server response.
tls_clientSocket.send(base64.b64encode(bytes('[email protected]','utf-8')))
tls_clientSocket.send(bytes('\r\n','utf-8'))
tls_clientSocket.send(base64.b64encode(bytes('password','utf-8')))
tls_clientSocket.send(bytes('\r\n','utf-8'))
recv = tls_clientSocket.recv(1024)
print (recv),
if recv[:3] != "220":
print ('220 Login: reply not received from server.')

# Send MAIL FROM command and print server response.
mailFromCommand = 'MAIL From: <[email protected]>\r\n'
tls_clientSocket.send(bytes(mailFromCommand,'utf-8'))
recv2 = tls_clientSocket.recv(1024)
print (recv2)

if recv2[:3] != "250":
print('250 reply not received from server.')

# Send RCPT TO command and print server response. RCPT TO is recipient, like where the email goes to
rcptToCommand = "RCPT TO: <[email protected]>\r\n"
tls_clientSocket.send(bytes(rcptToCommand,'utf-8'))
recv3 = tls_clientSocket.recv(1024)
print (recv3)

if recv3[:3] !="250":
print ('250 reply not received from server.')

# Send DATA command and print server response.
dataCommand = "DATA\r\n"
tls_clientSocket.send(bytes(dataCommand,'utf-8'))
recv4 = tls_clientSocket.recv(1024)
print (recv4)

if recv4[:3] != '250':
print ('Data:250 reply not received from server.')

# Send message subject, body and data
tls_clientSocket.send(bytes(msg,'utf-8'))

# Message ends with a single period.
tls_clientSocket.send(bytes(endmsg,'utf-8'))

# Send QUIT command and get server response.
quitCommand = 'QUIT\r\n'
tls_clientSocket.send(bytes(quitCommand,'utf-8'))
recv5 =tls_clientSocket.recv(1024)
print (recv5)

if recv5[:3] != '221':
print ('Quit:221 reply not received from server.')
38 changes: 38 additions & 0 deletions UDP Heartbeat/PingServer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# We will need the following module to generate randomized lost packets
import random
from socket import *
import time
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('127.0.0.1', 12000))
serverSocket.settimeout(5)

print(' ===== UDP Heartbeat Server =====')
print( 'Waiting to hear client heartbeats (5 sec timeout)...')
print("")
print("")
bufferMsg,address = serverSocket.recvfrom(1024)
print(" * * * client at: " + str(address) +" is online * * *")

t0 = time.time()
while True:
try:
# Receive the client packet along with the address it is coming from
message, address = serverSocket.recvfrom(1024)
#receMsg = message.decode('UTF-8') #decode message into string
#receMsg.split(" ")
# If rand is less is than 4, we consider the packet lost and do not respond
#if rand < 4:
# print("packet has been lost!")
# break
#continue
# Otherwise, the server responds
print ("SequenceNo.:"+str(message)+"("+str(round(time.time()-t0,2))+") s since last packet")
t0 = time.time()
serverSocket.sendto(message, address)
except timeout:
print(" Client at " + str(address) + "went OFFLINE")
serverSocket.settimeout(None)
Loading

0 comments on commit cbb7c73

Please sign in to comment.