EE450 SocketProgrammingProject Fall2015
EE450 SocketProgrammingProject Fall2015
EE450 SocketProgrammingProject Fall2015
DueDate:ThursdayNov19th,201511:59PM(Midnight)
(ThedeadlineisthesameforalloncampusandDENoffcampus
students)
HardDeadline(Strictlyenforced)
The objective of this assignment is to familiarize you with UNIX socket programming. This
assignmentisworth 10%
ofyouroverallgradeinthiscourse.
It is an individual assignment and no collaborationsareallowed.Anycheatingwillresult
inanautomaticFinthecourse(notjustintheassignment).
If you have any doubts/questionspleasefeelfreetocontact theTAsandccProfessorZahid, as
usual.Beforethat,makesureyouhave readthewholeprojectdescriptioncarefully .
ProblemStatement:
In this project you will be simulating a system similar to Dijkstra tobuildamapof the
network topology. A set of neighborinformationwill bedistributedamong four servers.
There will also be a client who is going to initiate the process and also do some
computation to give the final topology output. The client and servers are going to
communicate with each other to get the neighbor informations from the others and
combine all this informationtogether tobuildtheentiremapofthenetwork.Theoriginal
map isaconnected graph,whichmaycontain cycles (or loops).So later,basedonthe
map,theclient will calculatetheminimumspanningtree(MST)ofthenetworkandprint
itoutontheterminal.
The servers will communicate with the client using TCP sockets. The client will
communicatewiththeserversusingUDPsockets.
InputFilesUsed:
The files specified below will be used as inputs in your programs in order to dynamically
configure the state of the system. The contents ofthefilesshouldNOTbe hardcoded inyour
source code, because during grading, the input files will bedifferent,buttheformatsofthefiles
willremainthesame.
1. serverA.txt: This inputfile contains the neighbors namesandcorrespondinglinkcosts
from the serverA toeachneighbor.Itwillcontainseveralrows,whereeachrowhasthe
neighbors name and the corresponding link cost (during grading, we will change the
contents,buttheformatwillremainthesame) :
serverB 20
serverC 10
serverA 20
serverC 30
serverD 15
serverA 10
serverB 30
serverB 15
SourceCodeFiles
Your implementation should include the source code files described below, for each
componentofthesystem.
1. S
erver A, B, C and D: You must use one of these names for this piece of code:
server#.c or
server#.cc
or
server#.cpp(all small letters).Alsoyoumust call the
corresponding header file (if you have one it is not mandatory)
server#.h (all
small letters).The #character must be replaced bytheserveridentifier(i.e.Aor
BorC orD), dependingonwhich serveritcorresponds to.In caseyouareusing
one executable for all four servers (i.e. if you choose to make a fork based
implementation), you should use the same namingconvention without adding the
servers ID at the end of the file name (e.g. .c).
server In order to create four
servers in your system using one executable, you can use the fork() function
insideyour servers codeto create4childprocesses.Youmustfollowthisnaming
convention!Thispieceofcodebasicallyhandlestheserverfunctionalities.
Client
2. :
The name of this pieceofcodemust be
client.cor
client.ccor
client.cpp
(all smallletters)and the header file(ifyouhaveoneitisnotmandatory)mustbe
calledclient.h (allsmallletters).
.
MoreDetailedExplanations:
Phase1:(20points)
In this phase, each server creates a UDP server socketwhereitlistensforincomingmessages
from the client (seeTable1forthestaticportnumberstobeassignedtotheservers).Theclient
will also create a TCP server socket to listen for incoming connectionsfromservers(seeTable
1forthestaticportnumbertobeassignedtotheclient).
When each server first loads, it will read the content of a file containing its neighbors
information. ThefilenameforServerAwillbe serverA.txt andthefilenameforServerB willbe
serverB.txt , so on. Then it saves the information insomekindof datastructuresuchasarray
ormatrixorlinklistetc.Thesampleofthefilecontentareprovidedinthe InputFiles
section.
Whentheclientfirstbootsup,it DOESNT needtoreadfromanyfile.
Phase2:(60points)
InPhase1,youreadtheneighborinformationofeachserver.Inotherwords,eachservernow
understandswhichotherserversitcanconnecttoandthe'cost'associatedwitheachlink
connection.ThegoalofPhase2isforeachnodetoobtaintheentiretopologyofthenetwork,
usingtheconnectivityinformationofeachnode.Theprincipleissimilartothe
linkstate
advertisement usedinprotocolssuchasOSPF.
Thetopologyofthenetworkisrepresentedasanundirected graph.Therearevariouswaysin
whichyoumayrepresentagraphwhilecoding.Forthisproject,weshalluseanadjacency
matrix.Foragraphcontainingnnodes,anadjacencymatrixisannxnmatrixconsistingof0's
and1'sthatindicatesifanodeisconnectedtoanother.Forexample,considertheadjacency
matrixofthe6nodegraphgivenbelow.
Youcanfindsimilarexamplesofadjacencymatricesatthe Wikipediapage.
Fortheoutputofphase2, eachserverandtheclientshouldprinttheadjacencymatrixofthe
networkthattheyarepartof.Since,theyareallpartofthesamenetworktheyshouldideally
printthesameadjacencymatrix.Notethatinitiallyeachserverandclientonlyknowsthe
server/client(s)thattheyareconnectedto.Eachserver,nowhastoconveyitsconnectivity
informationtoalltheothernodesandclient.UseTCPorUDPconnections(asapplicable)to
transmitconnectivityinformation.Attheendofphase2eachnodeshouldhaveanadjacency
matrixcorrespondingtoitsviewofthenetworkbasedontheinformationthatithasreceived
fromtheothernodesinthenetwork.Theadjacencymatrixmusthavethefollowingformat:
Server A B C D
Inourproject,basedontheexampleinputfilesgivenabove,thenetworktopologyisillustrated
infigure1.Sinceinthisnetworktopology,eachlinkcostisalsogiven.Sotoincorporatelink
costinformationintotheadjacencymatrixaswell,wecanreplacevalue1sasthe
correspondinglinkcost(Note,forthediagonalentriesintheadjacencymatrix,theystillremain
as0s).Thecorrespondingadjacencymatrixisasfollows:
Asanexercise,wesuggestyouwritedowntheadjacencymatrixfortheillustrativenetwork
givenbelow:
figure1.Illustrationofthenetwork
Therearemultiplewaysbywhichyoucanensurethatallserversagreeontheirviewofthe
network.Onewayisfortheserverstocommunicateamongthemselves,eachserver
disseminatingitsviewofthenetworktilleveryonesettlesdownonthecompleteview. Forthe
purposesofthisassignment,however,weshallfollowasimplerstrategy .Eachserver
shallcommunicateitsviewofthenetwork(i.e,itsconnectivityinformation)totheclient.Now
thattheclienthastheconnectivityinformationofalltheservers,itcanconstructtheirnetwork
topology.Theclientthenbroadcaststhistopologytotheservers.Specifically,the
communicationamongtheclientandserversisstructuredasfollows:
TheserverssharetheirneighborinformationtotheclientthroughTCP.Namely,the
followingconnectionsneedtobeviaTCP:
ServerAtoClient
ServerBtoClient
ServerCtoClient
ServerDtoClient
Theclient'broadcasts'thenetworktopologytotheserversthoughUDP. Whileweuse
theterm'broadcast'here,forimplementationpurposesmaketheclientopen
unicastUDPconnectionswitheachoftheserversandtransmitthesamedata
individually. Thus,wehavethefollowingUDPconnections:
ClienttoServerA
ClienttoServerB
ClienttoServerC
ClienttoServerD
Phase3:
(20points)
AttheendofPhase2,allclientandservershavetheentiretopologyofthenetworkwithlink
costs.InPhase3,thistopologyisusedtocalculateatreeoraminimumspanningtreethat
containallservers.
Tree:
Atreeisanundirectedgraphinwhichanytwonodesareconnectedbyexactlyonepath.This
meansthatthereisnoloopsinatree.Anexampleofatreeisthefollowinggraph.
Source: Wikipedia|Tree
Itiseasytoseethatfromaconnectedgraph,wecanconstructatreefromit
withoutusingany
linkcosts .Infact,manytreesmightbeconstructedfromasinglegraph.
Minimumspanningtree:
Givenaconnectedgraphcontainingnodesandlinkswithlinkcosts, wesaythatthecostofa
tree,constructedfromagivengraph,isthesumofalllinkcostsofthetree. Forexample,
givenagraphbelow,twotreeshavethesamecost,whichis16.
Source:Wikipedia|Minimumspanningtree
Aminimumspanningtreeisatreewiththesmallestcost.Infact,thetreesintheabove
exampleareminimumspanningtrees.(Youcantrytofindothertreesandtheircostwillbeat
least16.)
Now,youhavetheknowledgeoftreesandminimumspanningtrees.InPhase3,theclient
constructsatreecontainingallservers .Belowisthegradingcriteriaofthisphase.Theterm
treebelowrepresentsatreethatcontainsallservers.
Iftheoutputisatree,10pointsareobtainedinthisphase.
Iftheoutputisaminimumspanningtree,20pointsareobtainedinthisphase.
Hint:Atreethatcontainsallnodesinagivengraphiscalledaconnectedtree.Aconnected
treecanbeverifiedbyseveralmethods.Anefficientmethodistoruneither
depthfirstsearch
or
breadthfirstsearch
algorithmandchecksthatanoutputsetofnodescontainsallnodesin
thegraph.
Hint:Doyouneedtoverifythatatreeisconnectedifitisaminimumspanningtree?
Asasidenote,theminimumspanningtreeisusedinalayer2switchnetworktoavoid
loopsinthenetworkwherethecalculationisdonedistributively.Inthisproject,the
processissimplifiedbylettingtheclientcalculatetheminimumspanningtree.
Table1.StaticandDynamicassignmentsforTCPandUDPports.
Process DynamicPorts StaticPorts
Event OnScreenMessage
UponReadingthefile TheServerAhasthefollowingneighborinformation:
NeighborCost
_______ ____. (Repeat this line basedonthenumber
of entries. e.g. if you have three entries, you should print
thislinethrice.Fortheexamplescenarioitwillbe.
NeighborCost
serverB20
)
serverC10
After sending its neighbor The Server A finishes sending its neighbor information to
informationtotheClient the Client with TCP port number ___ and IP address ___
(ClientsTCPportnumberandIPaddress).
For this connection with the Client, the ServerA has
TCP
portnumber_____andIPaddress_____.
After receiving the network The server A has received the network topology fromthe
topologyfromtheClient Client with UDP port number ___ and IP address _____
(ClientsUDPportnumberandIPaddress)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
For thisconnection withClient,TheServerAhasUDPport
number_____andIPaddress_____.
Table3.ServerBonscreenmessages
Event OnScreenMessage
UponReadingthefile TheServerBhasthefollowingneighborinformation:
NeighborCost
_______ ____. (Repeat this line basedon thenumber
of entries. e.g. if you have three entries, you should print
thislinethrice.Fortheexamplescenarioitwillbe.
NeighborCost
serverA 20
serverC 30
serverD 15
)
After sending its neighbor The Server B finishes sending its neighbor information to
informationtotheClient the Client with TCP port number ___ and IP address___
(ClientsTCPportnumberandIPaddress).
For this connection with the Client, theServerB has
TCP
portnumber_____andIPaddress_____.
After receiving the network The server B has received the network topology from the
topologyfromtheClient Client with UDP port number ___ and IP address _____
(ClientsUDPportnumberandIPaddress)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
For thisconnectionwithClient,TheServerBhasUDPport
number_____andIPaddress_____.
Table4.ServerConscreenmessages
Event OnScreenMessage
BootingUp TheServerChasUDPportnumber_____andIPaddress
_____.
UponReadingthefile TheServerChasthefollowingneighborinformation:
NeighborCost
_______ ____. (Repeat this line basedon thenumber
of entries. e.g. if you have three entries, you shouldprint
thislinethrice.Fortheexamplescenarioitwillbe.
NeighborCost
serverA 10
serverB 30
)
After sending its neighbor The Server C finishes sending its neighbor information to
informationtotheClient the Client with TCP port number ___ andIP address___
(ClientsTCPportnumberandIPaddress).
For this connection withthe Client, theServerC has
TCP
portnumber_____andIPaddress_____.
After receiving the network The server C has received the network topologyfromthe
topologyfromtheClient Client with UDP port number ___ and IP address _____
(ClientsUDPportnumberandIPaddress)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
ForthisconnectionwithClient,TheServerChasUDPport
number_____andIPaddress_____.
Table5.ServerDonscreenmessages
Event OnScreenMessage
BootingUp TheServerD hasUDPportnumber_____andIPaddress
_____.
UponReadingthefile TheServerDhasthefollowingneighborinformation:
NeighborCost
_______ ____. (Repeat this line basedon thenumber
of entries. e.g. if you have three entries, you should print
thislinethrice.Fortheexamplescenarioitwillbe.
NeighborCost
serverB 15
)
After sending its neighbor The Server D finishes sending its neighbor information to
informationtotheClient the Client with TCP port number ___ andIP address___
(ClientsTCPportnumberandIPaddress).
For this connection withthe Client, theServerD has
TCP
portnumber_____andIPaddress_____.
After receiving the network The server D has received the network topologyfromthe
topologyfromtheClient Client with UDP port number ___ and IP address _____
(ClientsUDPportnumberandIPaddress)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
For thisconnectionwithClient,TheServerDhasUDPport
number_____andIPaddress_____.
Table6.Clientonscreenmessages
Event OnScreenMessage
BootingUp The Client has TCP port number _____ and IP address
_____.
After sending the network The Client has sent the network topology to the network
topologytotheServerA topology totheServerAwithUDPportnumber___andIP
address _____ (Server As UDP port number and IP
address)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
ForthisconnectionwithServerA,TheClienthasUDPport
number_____andIPaddress_____.
After sending the network The Client has sent the network topology to the network
topologytotheServerB topology totheServerBwithUDPportnumber___andIP
address _____ (Server Bs UDP port number and IP
address)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
ForthisconnectionwithServerB,TheClienthasUDPport
number_____andIPaddress_____.
After sending the network The Client has sent the network topology to the network
topologytotheServerC topology totheServerCwithUDPportnumber___ andIP
address _____ (Server Cs UDP port number and IP
address)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
ForthisconnectionwithServerC,TheClienthasUDPport
number_____andIPaddress_____.
After sending the network The Client has sent the network topology to the network
topologytotheServerD topology totheServerDwithUDPportnumber___ andIP
address _____ (Server Ds UDP port number and IP
address)asfollows:
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BC30
BD15)
ForthisconnectionwithServerD,TheClienthasUDPport
number_____andIPaddress_____.
Afteratreeiscalculated The Client has calculated a tree. The tree cost is ____
(costofthetree):
EdgeCost
____ ____ (Repeat this linebased on thenumberof
edges in the network topology. e.g. For the example
scenarioitwillbe.
EdgeCost
AB20
AC10
BD15)
Assumptions:
1. Itisrecommendedtostarttheprocessesinthisorder:serverA,serverB,serverC,
ServerD,andclient.
2. If you need to have more code files than the ones that are mentioned here,
please use meaningful names and all small lettersand mention them all in your
READMEfile .
3. You are allowed to use blocks of code from Beejs socket programming tutorial
(Beejs guide to network programming) in your project. However, you need to
markthecopiedpartinyourcode.
4. When you run your code, if you get the message port already in use or
address alreadyin use, pleasefirstchecktoseeif youhaveazombieprocess
(from past logins or previous runs of code that are still not terminated andhold
the port busy). If you do not have such zombie processes or if you still get this
message after terminating all zombieprocesses, trychangingthe static UDP or
TCP port number corresponding to this error message (all port numbers below
1024 are reserved and must not be used). If you have to change the port
number, pleasedomentionitinyourREADMEfile .
Requirements:
1. Do not hardcode the TCP or UDP port numbers that are to be obtained
dynamically. Refer to Table1 toseewhich portsarestatically definedandwhich
ones are dynamically assigned. Use getsockname() function to retrieve the
locallybound port number wherever ports are assigned dynamically as shown
below:
//Retrieve the locallybound name of the specified socket and store it in the sockaddr
structure
getsock_check=getsockname(TCP_Connect_Sock,(struct sockaddr *)&my_addr,
(socklen_t*)&addrlen)
//Errorchecking
if(getsock_check==1){
perror("getsockname")
exit(1)
}
3. Youcaneitherterminateallprocessesaftercompletionofphase3orassumethat
theuserwillterminatethemattheendbypressingctrlC.
4. All the naming conventions and the onscreen messages must conform to the
previouslymentionedrules.
5. You are not allowed to pass any parameter or value orstringor characterasa
commandlineargumentexceptforchoosingthetimingslotsinphase2.
7. Using fork() or similar system calls are not mandatory if you do not feel
comfortableusingthemtocreateconcurrentprocesses.
Programmingplatformandenvironment:
Allyourcodesmust run on
1. nunki
(nunki.usc.edu)andonly nunki .ItisaSunOS
machineatUSC.Youshouldallhaveaccessto nunki,
ifyouareaUSCstudent.
3. NoMSWindowsprogramswillbeaccepted.
You must use only C/C++ on UNIX as well as UNIX Socket programming commands
and functions. Here are the pointers for Beej's Guide to C Programmingand Network
Programming(socketprogramming):
http://www.beej.us/guide/bgnet/
http://www.beej.us/guide/bgc/
Once you run xwin andopen an ssh connectiontonunki.usc.edu, you canuse a unix
texteditorlikeemacs to typeyourcode and then use compilers such as g++(forC++)
andgcc(forC) that are alreadyinstalled on nunki tocompileyourcode.Youmustuse
the following commands and switchesto compile yourfile.c oryourfile.cpp.Itwillmake
anexecutablebythenameof"yourfileoutput.
DoNOTforgetthemandatorynamingconventionsmentionedbefore!
Also inside your code you need to include these header files in addition to any other
headerfileyouthinkyoumayneed:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<netdb.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/wait.h>
SubmissionRules:
1. Alongwithyourcodefiles,includea READMEfile .Inthisfilewrite
a. Your Full
Name asgivenintheclasslist
b. YourStudentID
c. Whatyouhavedoneintheassignment
d. What your code files are and what each one of them does. (Please do not
repeat the project description, just name your code files and briefly mention
whattheydo).
e. What the TA should do to run your programs. (Any specific order of events
shouldbementioned.)
f. Theformatofallthemessagesexchanged.
g. Any idiosyncrasy of your project. It should say under what conditions the
projectfails,ifany.
h. Reused Code: Did you use code from anywhere for your project? If not,say
so. If so,say what functions and wherethey're from.(Also identifythiswitha
commentinthesourcecode.)
SubmissionsWITHOUTREADMEfilesWILLNOTBEGRADED
.
4. Right after submitting the project, send a oneline email to your designated TA
(NOT all TAs) informing him or her that you have submitted the project to the
Digital Dropbox. Please do NOT forget to email the TA or your project
submissionwillbeconsideredlateandwillautomaticallyreceiveazero.
5. You will receive a confirmation email from the TA to inform you whether your
project is received successfully,sopleasedocheck your emailswell beforethe
deadlinetomakesureyourattemptatsubmissionissuccessful.
6. You must allowat least12hoursbefore the deadlineto submit your project and
receivetheconfirmationemailfromtheTA.
8. Please take into account all kinds of possible technical issuesanddo expecta
huge traffic on the DEN website very close to the deadline which may render
yoursubmissionorevenaccesstoDENunsuccessful.
9. Please do not wait till the last 5 minutes to upload and submit your project
because you will not have enough time to email the TA and receive a
confirmationemailbeforethedeadline.
GradingCriteria:
Yourprojectgradewilldependonthefollowing:
1. Correct functionality, i.e. how well your programs fulfill the requirements of the
assignment,speciallythecommunicationsthroughUDPandTCPsockets.
3. WhetheryourprogramsworkasyousaytheywouldintheREADMEfile.
4. Whetheryourprogramsprintouttheappropriateerrormessagesandresults.
6. If your submitted codes, compile but when executed, produce runtime errors
withoutperforminganytasksoftheproject,youwillreceive10outof100.
9. If your code compiles and performs all tasks of all 3 phases correctly and
errorfree, and your README file conforms to the requirements mentioned
before,youwillreceive100outof100.
10. If you forget to include any of the code files or the README file in the project
tarball that you submitted, you will lose 5 points foreachmissingfile (plusyou
needtosendthefiletotheTAinorderforyourprojecttobegraded.)
12. Youwilllose5pointsforeacherrororataskthatisnotdonecorrectly.
13. Theminimumgradeforanontimesubmittedprojectis10outof100.
15. Using fork() or similar system calls are not mandatory however if you do use
fork() or similar system files in your codes to create concurrent processes (or
threads)andtheyfunctioncorrectlyyouwillreceive10bonuspoints.
16. If you submit a makefile or a script file along with your project that helps us
compileyourcodesmoreeasily,youwillreceive5bonuspoints.
17. We also encourage you to discuss homework and project problems onPiazza.
We will give those who actively help others out by answering questions on
Piazza upto 5 bonuspoints.(
If youwantto earn theextracredits,doremember
toleaveyournamesvisibletoinstructorswhenansweringquestionsonPiazza. )
19. Your code will not be altered in any ways for grading purposes and however it
willbetestedwithdifferentinputfiles.YourdesignatedTArunsyourprojectasis,
according to the project description and your README file and then check
whetheritworkscorrectlyornot.
CautionaryWords:
1. Startonthisprojectearly!!!
3. You may create zombie processes while testing your codes, pleasemakesure
you kill them every time you want to run your code. To see a listof all zombie
processes even from your past logins to nunki, try this command: ps aux |
grep<your_username>
4. Identify the zombie processes and their process number and killthem by typing
atthecommandline:
Kill9processnumber
5. There is a cap on the number of concurrent processes that you areallowed to
run on nunki. If you forget to terminate the zombie processes, theyaccumulate
andexceed thecap and youwill receivea warningemailfromITS.Pleasemake
sureyouterminateallsuchprocessesbeforeyouexitnunki.
6. Pleasedoremembertoterminateallzombieorbackgroundprocesses,otherwise
they hold theassignedportnumbersandsocketsbusyandwewillnotbeableto
runyourcodeinouraccountonnunkiwhenwegradeyourproject.
AcademicIntegrity:
Allstudentsareexpectedtowritealltheircodeontheirown.