计算机网络实验

2018-10-18  本文已影响0人  码力平平菜鸡熊

计算机网络实验:搭建一个简单的web server 和 SMTP 客户端。

只要熟悉了socket编程, HTTP request 、response的内容和SMTP发送的格式,一切均可以解决。

主要是状态码的识别和文件目录的提取,简单的字符串处理即可。

1.Super simple Web Server

#!usr/bin/env

# import socket module

from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)

# Prepare a sever socket

serverSocket.bind(('', 6789))  # 将TCP欢迎套接字绑定到指定端口

serverSocket.listen(5)  # 最大连接数为5

while True:

    # Establish the connection

    print('Ready to serve...')

    connectionSocket, addr = serverSocket.accept()  # 接收到客户连接请求后,建立新的TCP连接套接字

    try:

        message = connectionSocket.recv(1024)  # 获取客户发送的报文

        filename = message.split()[1]

        f = open(filename[1:])

        outputdata = f.read()

        # Send one HTTP header line into socket

        header = ' HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/html\nContent-Length: %d\n\n' % (

            len(outputdata))

        connectionSocket.send(header.encode())

        # Send the content of the requested file to the client

        for i in range(0, len(outputdata)):

            connectionSocket.send(outputdata[i].encode())

        connectionSocket.close()

    except IOError:

        # Send response message for file not found

        header = ' HTTP/1.1 404 Found'

        connectionSocket.send(header.encode())

        # Close client socket

        connectionSocket.close()

    # serverSocket.close()

2.Super simple SMTP Client

from socketimport *

import logging

logging.basicConfig(filename='./SMTP_LOG'+__name__+'.log',format='[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]', level = logging.INFO,filemode='a',datefmt='%Y-%m-%d%I:%M:%S %p')

msg ="\r\nI love computer networks\r\n.\r\n"

LOG_FILE ='tst.log'

mailserver = ('mail.bjtu.edu.cn', 25)

try:

clientSocket = socket(AF_INET, SOCK_STREAM)

clientSocket.connect(mailserver)

recv = clientSocket.recv(1024).decode()

logging.info(recv)

if recv[:3]!='220':

raise Exception('未与服务器连接\n')

heloCommand =b"HELO BJTU\r\n"

    clientSocket.send(heloCommand)

recv1 = clientSocket.recv(1024).decode()

logging.info(recv1)

if recv[:3]!='220':

raise Exception('服务器无应答\n')

clientSocket.send(b"auth login\r\n")

auth_recv = clientSocket.recv(1024).decode()

if auth_recv[:3] !='334':

raise Exception('登陆失败\n')

mail_id =b"就不告诉你\r\n"

   mail_password =b"知道了也没用\r\n"

   clientSocket.send(mail_id)

recv_id = clientSocket.recv(1024).decode()

if recv_id[:3] !='334':

raise Exception('用户ID错误!\n')

logging.info(recv_id)

clientSocket.send(mail_password)

recv_pass = clientSocket.recv(1024).decode()

logging.info(recv_pass)

if  recv_pass[:3]!='235':

raise Exception('用户密码错误!\n')

else:

print('Login successfully!')

mail_from =b"MAIL FROM: <16281150@bjtu.edu.cn>\r\n"

    clientSocket.send(mail_from)

recv2 = clientSocket.recv(1024).decode()

logging.info(recv2)

if recv2[:3] !='250':

raise Exception('MAIL FROM 输入错误!\n')

RCPT_TO =b"RCPT TO: <474600817@qq.com>\r\n"

    clientSocket.send(RCPT_TO)

recv3 = clientSocket.recv(1024).decode()

if recv3[:3] !='250':

raise Exception('RCPT TO输入错误!\n')

logging.info(recv3)

DATA =b"DATA\r\n"

    clientSocket.send(DATA)

recv4 = clientSocket.recv(1024).decode()

if recv4[:3] !='354':

raise Exception('蜜汁错误!\n')

logging.info(recv4)

clientSocket.send(msg.encode())

recv5 = clientSocket.recv(1024).decode()

if recv5[:3] !='250':

raise Exception('信息传送错误!\n')

logging.info(recv5)

QUIT =b"QUIT\r\n"

    clientSocket.send(QUIT)

recv6 = clientSocket.recv(1024).decode()

if recv6[:3] !='221':

raise Exception('退出错误!\n')

clientSocket.send(QUIT)

print("Successful!")

except Exception as e:

print('Exception Occur')

logging.exception(e)

其中SMTP部分的代码加入了异常处理和Log的初步使用,为今后的软件开发奠定基础

上一篇下一篇

猜你喜欢

热点阅读