SCC. 203程序 写作、Python程序语言调试

” SCC. 203程序 写作、Python程序语言调试SCC. 203 Computer Networks 1Practical 1 Network Application DevelopmentCoursework Weight: 60%In this practical, you will develop a number of small networking-based applications. Theseare designed to increase your competency in developing socket-based applications, as wellas increasing your familiarity with a number of key technologies and measures. These are inwidespread use, and commonly deployed to evaluate networks and to provide services overthem.During this practical, you will become familiar with the concept of network sockets andbegin to understand how they are Used. Sockets are a programming abstraction designed toassist us in building applications that use the network. We can treat these the same as anyother resource; writing to a socket sends a packet into the network, whilst reading from asocket provides us with the contents of the packet. We can do this in much the same wayas we would read and write to any file found on the local filesystem.Practical Lab StructurePractical 1 is split into a number of smaller tasks: ICMP Ping Client, Traceroute Client, WebServer and Web Proxy. Importantly, the tasks build upon each other; the work you do inTask 1.1 will be fundamental to Task 1.2, and similarly, the work completed in Task 2.1 willgreatly assist you in Task 2.2.For assessment purposes, 0nly Task 1.2 and Task 2.2 will be marked.Although Task 1.1 and Task 2.1 will not be assessed, it is still vital that youcomplete them, as they will provide the foundation for the later tasks.For those tasks that are assessed, you will be awarded for meeting certain criteria. Theseare outlined in more detail within Each task description. You are encouraged to progress asfar as possible with each task. Do note however, that Task 1 and Task 2 are independent;attempting both is advised, even if you do not fully complete each.Changes due to Online DeliveryThis course uses a dedicated virtual machine image for the purposes of these labs. Inprevious years, this would have been accessible via the PCs in the physical labs.With the move to online delivery, we are replicating this experience with three possibleoptions, which cover most Situations. If there are any issues with these, please get in touchwith the teaching team as soon as possible and we will assist you the best we can.Running the Virtual Machine LocallyThe virtual machine used for this task (and the second coursework) can be fetched andinstalled on your own local machine. This comes with some caveats including having theavailable resources free to use. For more details, please see the following guide (you mustPractical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 2be connected to the Lancaster University VPN to access this page and fetch the resourceswithin): https://scc-vagrant.lancs.Ac.uk/help/running_own_vm.htmlRunning the Code LocallyIt is also possible to run the code locally on your machine (directly and without a VM). Todo so, you will need a regular install of Python 3 (3.6+ recommended). As this task does notuse any external libraries (see Python Library Usage section below), this should berelatively easy to achieve.Details on how to install Python can be found here: httpss://www.python.org/downloads/Please note that you will still need the virtual machine (as described in the sections aboveand below) for the next coursework, starting in Week 17.There are some caveats with this approach though (hence why we provide the virtualmachine). Although the Same Python code will run regardless of the environment, theunderling implementation (and therefore) behaviour can be different, including for many ofthe network-related libraries used in this practical. Particularly on the Windows platform(rather than MacOS or Linux), the results may be different (see the following resource tounderstand why: httpss://ibm.co/3pUECwq)Given the multitude of potential discrepancies and variance that may occur when runningcode locally, we will not provide direct support for the method; only the virtual machinebasedapproaches will be supported by the teaching team.If you do take this approach, also note that for the purposes of demonstration and marking,the provided virtual machine will (and must) be used. It is not an acceptable excuse to claimthat it worked on your Own machine, so at the very least, please ensure that it runs on theprovided virtual machine image (using one of the methods described in the sections belowor above) before submitting.Using a Remote Instance of the Virtual MachineIf the above options are not suitable, we have provided a remote instance of the virtualmachine, running on infrastructure hosted at Lancaster University. This provides an identicalexperience and allows access to the environment without having to meet the hardwareresource requirements of running the virtual machine or code locally. To access this, pleaseuse the following link and select the SCC 203 option: httpss://mylab.lancaster.ac.uk/These virtual instances can be accessed via a browser or a downloadable client; it isrecommended that the client is used as it offers a more stable experience. You may have toreload your browser once the client is installed for this to function correctly.Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 3Provided/Skeleton CodeTo help you structure your code and get started with each task, we have provided you withsome skeleton code, which should be available on the SCC.203 Moodle page. This file willeventually contain all the code you have developed in this lab and will be the one submittedat the end of your work. It contains a structure for the code, including some helperfunctions and empty Classes. It Also contains some pseudocode for some of the tasks to getyou started.Firstly, there is a function included to parse command line arguments given to the script(setupArgumentParser). This includes determining which function is called (ping,traceroute, web, proxy), as well as additional parameters used for each task. Some ofthese may be optional, particularly if they are part of the additional features associated witheach task.The code also includes the NetworkApplication class, which will be a parent to theclasses that you will develop in the coursework. It contains some useful methods that arecommon across tasks. This includes the checksum function, which calculates a checksumto be used in an ICMP packet (see T1.1 and T1.2). Furthermore, it also includes twomethods which should be used to print out the results generated in T1.1 and T1.2:printOneResult and printAdditionalDetails.Finally, it also includes four empty child classes (ICMPPing, Traceroute, WebServerand Proxy) which are to be used for providing the solutions to each task (T1.1, T1.2, T2.1and T2.2 respectively). In the case of ICMPPing and WebServer, they also include somepseudocode to guide you (please see sections T1.1 and T2.1 for more details).These classes inherit the NetworkApplication class, which will allow you to use theparents helper Methods (checksum, printOneResult andprintAdditionalDetails). These can be called using the super() function. Formore details on inheritance in Python, see here: httpss://docs.python.org/3/tutorial/classes.html#inheritanceEach class contains an __init__ method, which is called when the object is created(which is done once the command line arguments have been parsed, in this case). This is thestarting point for writing the code in each class, but additional methods can be created asrequired. Please do not change the method signature for any of these __init__ functions(always retain the passing of the args object).To be clear: you can add new methods and code to each of the main classes (ICMPPing,Traceroute, WebServer and Proxy), but the remaining structure, methods and codemust remain intact.For the purposes of plagiarism checking, this provided code will not be considered.Running your Python scriptPractical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 4Once you have the virtual machine setup, you are ready to begin. For this practical, you willbe building your applications using Python 3 (as installed on the virtual machine).To run a Python script, open a Terminal window, and navigate to the directory in which thefile you want to run is located. To run the script, simply use the following command:python3 NetworkApplications.pyPlease note the use of python3 rather than python: the default command refers toPython 2.7, which we are not using in this course. Using this will result in a differentoutcome and potential incompatibilities.When you first start this task, the provided code will run successfully (defaulting to pinginglancaster.ac.uk) but do Nothing.Python Library UsageYou are not expected to use any external libraries for this practical; doing so is strictlyprohibited. All tasks can be achieved fully with the use of standard Python libraries.We are also aware of a number of network and IP-orientated libraries that are includedwithin the standard Python distribution. These could potentially be used in different ways toassist in your implementation. However, as we are trying to build your understandingaround the fundamentals of computer networks, we ask that you do not use these for thispractical either.The teaching team believe it is vitally important that you grasp the technical details behindmany of these libraries, which do a good job of abstracting and obscuring the details. It is ofcourse perfectly acceptable to use these libraries in any future software development youmay do, whether this be as part of an upcoming course module or even after graduation.By following the provided structure and guidance, you will not need to use any of these. Ifyou are in any doubt about a whether or not you can use a particular library,please contact the course tutors to confirm.Submission and AssessmentThe submission for all work completed in this practical is due by the end of Week 16. Allcode should be included in a single file, titled: NetworkApplications.py.Automated TestingWith the move to online delivery, we anticipate additional time challenges when running inlabmarking sessions. To improve the efficiency of this process, we will be using some simpleautomated testing of your code to help guide the in-lab sessions.To help us in using this, we Would request that you follow the guidance described in theProvided/Skeleton Code and Submission and Assessment sections regarding modifyingprovided classes, methods and filenames.Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 5Failure to adhere to this will result in a slowed marking process, which will be detrimentalto all. If you are in any doubt about whether a change or modification is acceptable, pleasecontact the teaching team.Marking SessionDuring the marking session (scheduled for Week 17), you may be expected to demonstratethe functionality of each of these scripts, as directed by the teaching team. You will mainlybe assessed on functionality but expect to be able to walk-through and explain your code.As we will also be providing you with a few small snippets of code (to use in your ownsolution), you will not be expected to explain these in great detail. However, a generalunderstanding of how these functions work will be beneficial to your overall learning andcomprehension. There will also be a small proportion of marks available for a consistentcode style and useful commenting. Resilient code, using try and except statements tocatch errors is also preferred, and will be rewarded accordingly.Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 6Task 1.1: ICMP PingThe first task is to recreate the ping client discussed in Lecture 3: Delay, Loss Throughput.Remember that ping is a tool used to measure delay and loss in computer networks. Itdoes this by sending messages to another host. Once a message has reached that host, it issent back to the sender. By measuring the amount of time taken to receive that response,we can determine the delay in the network. Similarly, by tracking the responses returnedfrom our messages, we can determine if any have been lost in the network.ping traditionally uses Internet Control Message Protocol (ICMP) messages to achieve thisbehaviour. More details can be found in RFC792. For this task, we will be sending echorequest messages (with an ICMP type code of 8). These requests are useful to us because onreaching the client, the Client will respond with an echo reply message (with an ICMP typecode of 0). By timing the period of time elapsed between sending the request and receivingthe reply, we can accurately determine the network delay between the two hosts.Remember, you are recreating ping without the use of external libraries; they areexplicitly prohibited!Implementation TipsThere are a number of aspects to consider when writing your implementation. Carefullythink about the logic required; use a whiteboard if need be. A ping client sends one ICMPecho request message at a time and waits until it receives a response. Measuring the timebetween sending the message and receiving it will give us the network delay incurred intransit. Repeating this process provides us with a number of delay measurements over time,showing any deviation that may occur.To assist you in your implementation, we have provided pseudocode for this task. This canbe found in the provided code, specifically in the ICMPPing class. It contains suggestedfunctions, as well as an overview of functionality to be implemented by each. These aregiven as comments and are to be treated as guidance only. Note that you may have tochange the parameters passed to each function as you advance with the task. The followingPython libraries will also be useful to your implementation: httpss://docs.python.org/3/library/socket.html httpss://docs.python.org/3/library/struct.html httpss://docs.python.org/3/library/time.html httpss://docs.python.org/3/library/select.html httpss://docs.python.org/3/library/binascii.htmlIt is possible to use both socket.SOCK_RAW and socket.SOCK_DGRAM when creatingsockets. SOCK_RAW requires privileges, as it gives you a huge amount of control and powerover the type and content of packets sent through it (for better or worse!). As such, itrequires sudo to work.In normal circumstances, a non-privileged version would probably be preferable; you dontPractical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 7always have privileges on a system. This is where SOCK_DGRAM comes in. However, itappears that SOCK_DGRAM, when used to specifically to send ICMP packets, is also aprivileged operation within some flavours of Linux (and on the provided VM).For the purposes of this practical, it is therefore recommended that you use SOCK_RAW,and run your Python Using sudo privileges.We have provided you with a checksum function (included in the NetworkApplicationparent class) which can be freely used in your solutions without penalty. It is important thatwhen passing a packet to this function, the checksum field must contain a dummy value of 0.Once the checksum has been calculated, it can be immediately inserted in the packet tosend.The ICMP header contains both an identifier and a sequence number. These can be used byyour application to match an echo request with its corresponding echo reply. It is also worthnoting that the data included in an echo request packet will be included in its entirety withinthe corresponding echo reply. Use these features to your advantage.Be warned that some servers will reject ICMP requests with an identifier of 0, so ensurethat this is set to a value 0.Please ensure that the printOneResult and printAdditionalDetails methods(and only these methods) are used for reporting the results.Debugging and TestingAny host, whether this be a PC, laptop, phone or server, should respond to a messagegenerated by your application. In reality, this is not always the case, as both networks andhosts can choose to disregard these packets and may do so for a number of reasons(including security). For the purposes of this task, using any well-known server is acceptable.As an example, the following popular sites will respond to an echo request: lancaster.ac.uk,google.com, or bbc.co.uk. These will all return with relatively low delays. To rigorously testyour application, using Servers located further afield will usually return larger delays. Forexample, the US Department of Education (www.ed.gov) can be queried.To confirm that the server you have chosen to test with does in fact respond to ICMP echorequest messages, feel free to use the existing built-in ping tool to verify reachability.Once you are sending packets, you can use the Wireshark tool to inspect these. Wiresharkwill also let you investigate the packets that you receive back. In both cases, it provides auseful method to ensure that these contain the expected information. This is a very usefultool for debugging, especially if you are getting unexpected errors; this will show exactlywhat is being sent from your script. Wireshark is installed in the virtual machine and can bestarted from the graphical interface. Once started, you can capture packets on the eth0interface (as highlighted in Figure 1). It may also be useful to filter packets to icmp only,using the filter bar found towards the top of the interface (also highlighted in Figure 1).Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 8Figure 1: Wireshark InterfaceCompletion CriteriaFor this task, we are looking for a functioning replica of the ping tool. That is, you cansuccessfully send and receive ICMP echo messages, timing the delay between. This is thenreported in the terminal window. Your application should continue to perform thesemeasurements until stopped.If you are unsure about the accuracy of the delay measured by your own tool, use the builtinping tool to confirm your results. Were not expecting the results to be perfectlyidentical (delay changes all the time) but showing that they are close is expected.Potential additional features include: Once stopped, show minimum, average and maximum delay across all measurements(use printAdditionalDetails method) Configurable measurement count, set using an optional argument (use countpositional argument) Configurable timeout, Set using an optional argument (use timeout positionalargument) Measuring and reporting packet loss, including unreachable destinations (useprintAdditionalDetails method)Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 9 Handling different ICMP error codes, such as Destination Host Unreachable andDestination Network UnreachableAs with the rest of this task, you do not have to completely implement these features, as nomarks will be awarded for Task 1.1. The features listed above may assist you in Task1.2 though; they are intentionally challenging and designed to stretch you.Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 10Task 1.2: TracerouteBuilding on Task 1.1, the second aspect of this task is to recreate the traceroute tool,again in Python. As discussed in Lecture 3: Delay, Loss Throughput, this is used to measurelatency between the host and each hop along the route to a destination. This too uses anICMP echo request message, but with an important modification: the Time To Live (TTL)value is initially set to 1. This ensures that we get a response from the first hop; thenetwork device closest to the host we are running the script on. When the message arrivesat this device, the TTL counter is decremented. When it reaches 0 (in this case at the firsthop), the message is returned to the client with an ICMP type of 11. This indicates that TTLhas been exceeded. As with the previous task, by measuring the time taken to receive thisresponse, delay can be calculated at each hop in the network. This process can be repeated,increasing the TTL Each time, until we receive an echo reply back (with an ICMP type of 0).This tells us that we have reached the destination, so we can stop the script.Implementation TipsAs with the previous task, make sure you think carefully about the logic here. Rememberyou can build upon your Task 1.1 implementation.As before, the provided checksum function included in the skeleton code can be usedwithout penalty.The same Python documentation as noted in Task 1.1 will be useful for this task too. Ofparticular note is the socket.setsockopt(level, optname, value) function,which can be used to set the TTL of a socket (and thus the packets leaving it): httpss://docs.python.org/3/library/socket.html#socket.socket.setsockoptFor this task, we rely on ICMP Type 11 error messages (TTL Exceeded). Unlike Type 0messages (Echo Reply), these do not contain an identifier field in the response. Any checkingyou might do in respect to this identifier will therefore fail (as it is not present).Please ensure that all code pertaining to this task is included in the Traceroute class.Please also check that the printOneResult and printAdditionalDetailsmethods (and only these methods) are used for reporting the results.Debugging and TestingAs with the previous task, every host on the path to your chosen destination shouldrespond to your echo request message. In reality, these messages are often filtered, includingwithin the lab network. As a result, it is especially difficult to test this tool with a remotehost. Instead, it is suggested that you test with a closer endpoint that is reachable:lancaster.ac.uk. Although the number of hops is small (~5), it can still be used todemonstrate the working of your application. If you run your script whilst attached to adifferent network, such as That at home, your results likely differ. You will also be able toreach external hosts more easily.Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 11The traceroute utility can be used to confirm the results generated by your ownapplication. This is installed on the virtual machine if you wish to use it. Be aware that bydefault, this tool actually sends messages over UDP instead of ICMP; this is done to avoidthe blocking discussed earlier. To force traceroute to send packets using ICMP, the -Iflag can be used. See the Linux man page for more details: httpss://linux.die.net/man/8/tracerouteAs with Task 1.1, Wireshark can be used to inspect the packets leaving your application.Comparing these to those created using the traceroute utility will provide you with ameaningful comparison.Marking CriteriaThe majority of marks will be awarded for ensuring that your implementation behaves in away similar to the traceroute utility. This includes providing delay measurements foreach of the nodes between your machine and the chosen remote host. You are expected toincrease the TTL of each message, until you reach this final destination.Additional marks will be awarded for the following aspects: Measuring and reporting packet loss, including unreachable destinations (useprintAdditionalDetails method) Repeated measurements for each node (present these as separate results using theprintOneResult method, each with the same TTL) Configurable timeout, set using an optional argument (use timeout positionalargument) Configurable protocol (UDP or ICMP), set using an optional argument (useprotocol positional argument) Resolve the IP addresses found in the responses to their respective hostnames (seeoptional destinationHostname variable in printOneResult method)As before, please note that the features mentioned above are considered supplementary;you do not have to complete them all, and you can still receive a satisfactory mark withoutcompleting any of them. They are intentionally challenging and designed to stretch you.Practical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 12Task 2.1: Web ServerFor the second task of this Practical, you will be building a simple HTTP web server. WebServers are a fundamental part of the Internet; they serve the web pages and content thatwe are all familiar with. You will be learning more about web servers and the operation ofthe HTTP protocol in Lecture 6: Web HTTP. Fundamentally, a web server receives aHTTP GET request for an object (usually a file), located on the web server. Once it receivesthis request, the web server will respond by returning this object back to the requester.As with the previous task, we will be using network sockets to build our application and tointeract with the network. The Web Server differs from the ICMP Ping application in that itwill bind to an explicit socket, identified by a port number. This allows the Web Server tolisten constantly for incoming requests, responding to each in turn. HTTP traffic is usuallybound for port 80, with port 8080 a frequently used alternative. For the purposes of thisapplication, we suggest you bind to a high numbered port above 1024; these areunprivileged sockets, which reduces the likelihood of conflict with existing running serviceson the virtual machine. For interest, application developers can register port numbers withthe Internet Assigned Numbers Authority (IANA), reserving them for their applicationsuse: httpss://www.iana.org/assignments/service-names-port-numbers/service-names-portnumbers.xhtmlThe application you build should respond to HTTP GET requests, and should be built toHTTP/1.1 specification, as defined in RFC2616. These requests will contain a Request-URI,which is used to define the path to the object requested. For example, a request with a URIof 127.0.0.1:8080/index.html, will serve a file name index.html found in thesame directory as the Python script itself. The URI is broken down as follows: 127.0.0.1: Hostname of web server 8080: Port number that web server has bound to index.html: File to be servedOn successfully finding and loading the file, it will be sent back to client with the appropriateheader. This will contain the Status-Code 200, meaning that the file has been found OK, andthat it will be delivered to the client as expected. Your implementation needs only servefiles from the same directory in Which the Python script is executed.Implementation TipsAs before, we have provided pseudocode that can be used to aid you in this task. This canbe found in the provided code, specifically in the WebServer class. It contains suggested asuggested function, as well as an overview of functionality to be implemented. This is givenas comments and are to be treated as guidance only. Note that you may have to changethe parameters passed to each function as you advance with the task. An example HTML file(index.html) is also provided in the same location. The following Python library and itsdocumentation may also serve as a pointer to helpful functions: httpss://docs.python.org/3/library/socket.htmlPractical 1 Network Application Development Lent Term, 2021SCC. 203 Computer Networks 13 httpss://docs.python.org/3/library/socketserver.htmlAs a baseline, your implementation needs only to be single-threaded. This allows amaximum of one request to be handled at a time.Debugging and TestingTo test your web server application, you must generate a valid request. There are a numberof tools to achieve this. For example, the curl utility can be used to generate a request(presuming your web server is running on port 8080):curl 127.0.0.1:8080/index.htmlAn equally valid method is to use a web browser, such as the Chromium Web Browserinstalled on the virtual machine. Simply point the browser to the same URL:127.0.0.1:8080/index.htmlIf you are unsure about what a HTTP request should look like, Wireshark can again be usedto inspect packets. This includes both the HTTP request and response. This will help youdebugging the form and Structure of your requests, identifying any issues that may bepresent. If you are still using Wireshark from the previous task, make sure to remove theicmp filter! https can be used instead. It will also be necessary to capture packets on theloopback interface (lo), rather than the external interface (eth0).If you wish to observe how a Web Server should behave (and examine the packetsgenerated by such), Python provides a handy way of starting a very simple HTTP serverimplementation:python -m SimpleHTTPServerRequests to this server can be made using the methods described previously.Completion CriteriaFor this task, you expected to build a functioning Web Server, capable of handling requestsfor content. You should be able to demonstrate that, given a request, the Web Server willreturn the correct file, as well as producing a well-formed response header with protocolve”

添加老师微信回复‘’官网 辅导‘’获取专业老师帮助,或点击联系老师1对1在线指导