




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
NetworkIntroductiontoComputerSystems24thLecture,Dec.12,2013XiangqunChen,JunlinLuReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEchoAProgrammer’sViewoftheHostsaremappedtoasetof32-bitIPThesetofIPaddressesismappedtoasetofidentifierscalledInte names79ismappedAprocessononeInte hostcancommunicatewithaprocessonanotherInte hostoveraconnection AsocketisanendpointofaAportisa16-bitintegerthatidentifiesaEphemeralport:AssignedautomaticallyandtemporarilyonwhenmakesaconnectionrequestWell-knownport:port80isassociatedwithWebAconnectionisuniquelyidentifiedbythesocketaddressesofidpoints(socketpair)(cliaddr:cliport,PuttingitallAnatomyofan socketaddress
Serversockethostaddress
51213isanephemeralportallocatedbythekernel
80isawell-knownportReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEcho -Server sends4.
sends Note:sandserversareprocessesrunningonhosts(canbethesameordifferenthosts) workapplicationsarebasedonthe-serverServerhandlerequestforresourcesExamplesofWebbrowsers, net,Howdoes findtheserver?IPaddr:portTheIPaddressintheserversocket entifiesthe(moreprecisely,anadapterontheThe(well-known)portintheserversocketaddre entifiestheservice,andthusimplicitlyidentifiestheserverprocessthatperformsthatservice.ExamplesofwellknowPort7:EchoPort23:netPort25:MailPort80:WebUsingPortstoIdentifyServerhosthost
(i.e.,theWeb
(port80)(port7)(i.e.,theecho(portEcho(port Serversarelong-runningprocesses(daemons程序Createdatboot-time(typically)bytheinitprocess(processRuncontinuouslyuntilthemachineisturnedEachserverwaitsforrequeststoarriveonawell-knownportassociatedwithaparticularservicePort7:echoPort netPort25:mailPort80:HTTPAmachhatrunsaserverprocessisalsooftenreferredasaServerWebserver(portResource:files/computecycles(CGIService:retrievesfilesandrunsCGIprogramsonbehalfofSee/etc/servicesforacomprehensivelistofSee/etc/servicesforacomprehensivelistoftheport sonaLinuxResource:Service:storesandretrievenetserverResource:Service:proxiesaterminalontheserverMailserver “spool”Service:storesmailmessagesinspoolReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEchoSocketsCreatedintheearly80’saspartoftheoriginalBerkeleydistributionofUnixthatcontainedanearlyversionofthe Providesauser-levelinterfaceto Underlyingbasisforall Basedon/serverprogrammingsocket Connect(IPaddr,port
Whatisa
Tothekernel,asocketisanendpointofToanapplication,asocketisafiledescriptorthatletstheapplicationread/writefrom/toth wrRemember:AllUnixI/Odevices,ludinworks,modeledas sandserverscommunicatewitheachotherbyreadingfromandwritingtosocketdescriptorsThemaindisttionbetweenregularfileI/OandsocketI/Oishowtheapplication“opens”thesocketdescriptorsOverviewoftheSockets Server打開 發(fā) 等/
requestfromnextSocketAddressGenericsocketForaddressargumentstoconnect,bind,andNecessaryonlybecauseCdidnothavegeneric(void*)pointerswhenthesocketsinterfacewasdesignedstructstruct{short/*protocolfamily/*addressSocketAddress -specificsocketMustcast(sockaddr_in*)to(sockaddr*)forconnect,bind,andacceptstructstructsockaddr_inunsignedshortunsignedshortstructin_addrunsignedchar/*addressfamily(always)/*portnum/*IPaddrworkbyteorderworkbyteorder*/sin_zero[8];/*padtosizeof(structsockaddr)*/ 00000000Example:Echoandgreatwhite>./echoserverigreatwhite>./echoserverilinux>serverconnectedserverconnectedtoBRYANT-TP4.VLSI.CS.CMU.EDU(9),port64690oserverreceived12type:OConnectionReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEcho
EchoMain lude/*usage:./echo hostport*/intmain(intargc,char**argv){ fd,char*host,buf[MAXLINE];rio_trio;host=argv[1];port=fd=Open_fd(host,
Sendlo
printf("type:");while(Fgets(buf,MAXLINE,stdin)!=NULL) fd,buf,from Rio_readlineb(&rio,buf,Fputs(buf,stdout);printf("type:");
} Connect在 fd函數(shù) OverviewoftheSockets Server
:open_int fd(char*hostname,int{int structhostent*hp;structsockaddr_in
Thisfunctionopensaconnectionfromthetotheserveratif(( fd=socket(AF_ ,SOCK_STREAM,0))<0)return-1;/*checkerrnoforcauseoferror*//*Fillintheserver'sIPaddressandportif((hp=gethostbyname(hostname))==return-2;/*checkh_errnoforcauseoferror*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ bcopy((char*)hp-(char*)&serveraddr.sin_addr.s_addr,hp->h_length);serveraddr.sin_port=htons(port);/*Establishaconnectionwiththeserver*/if(connect( fd,(SA*)&serveraddr,sizeof(serveraddr))<return-1; }
:open_socketcreatesasocketdescriptoronJustallocates&initializessomeinternaldata :indicatesthatthesocketisassociatedwith SOCK_STREAM:selectsareliablebytestreamfd;/*socketdescriptorif<fd=,SOCK_STREAM,return-1;/*checkerrnoforcauseoferror... :open_Thethenbuildstheserver’s /*socketdescriptorstructhostent*hp; /*DNShostentry*/structsockaddr_inserveraddr;/*server’sIPaddress*//*fillintheserver'sIPaddressandport*/if((hp=gethostbyname(hostname))==NULL)return-2;/*checkh_errnoforcauseoferror*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ serveraddr.sin_port=htons(port);bcopy((char*)hp-
ACarefulLookatbcopy/*DNShostentrystructure*/structhostent{.. /*lengthofanaddress,inbytes*/ **h_addr_list;/*null-terminatedarrayofin_addrstructsstructsockaddr_in..structin_addr /*IPaddriworkbyte./*Inteaddressstructure*/structin_addr{unsignedints_addr;workbyteorder(big-endian)structstructhostent/*DNShostentrystructsockaddr_inserveraddr;/*server’ssocketaddressbcopy((char*)hp->h_addr_list[0],/*src,dest(char*)&serveraddr.sin_addr.s_addr,hp-BcopyArgumentDatastruct ..0 struct0000000000000tructs :open_Finallythecreatesaconnectionwiththeprocesssuspends(blocks)untiltheconnectionisAfterresuming,the isreadytobeginexchangingmessageswiththeserverviaUnixI/Ocallsondescriptor /*socketdescriptor*/structsockaddr_inserveraddr; /*serveraddress*/typedefstructsockaddrSA; /*genericsockaddr*//*Establishaconnectionwiththeserverif fd,(SA*)&serveraddr,sizeof(serveraddr))return-1; }Reviewof ,connection,portRevisitofa-serverSocketinterface,EchosideServersideTestofEcho
EchoServer:Mainintmain(intargc,char**argv)intlistenfd,connfd,port, structsockaddr_ structhostent*hp;char*haddrp;unsigned port=atoi(argv[1]);/*theserverlistensonaportonthecommandlinelistenfd=while(1)len= connfd=Accept(listenfd,(SA*)& addr,& hp=Gethostbyaddr((constchar*)& addr.sin_addr.s_addr),AF_ haddrp= _port=ntohs( printf("serverconnectedto%s(%s),port%u\n",hp->h_name, }}OverviewoftheSockets
Officeephoneogyfor Buya lthelocaladministratorwhatnumberyouwanttouse Plugthephone Answerthephonewhenitrings=EchoServer:intopen_listenfd(int{intlistenfd,optval=1;structsockaddr_inserveraddr;/*/*Createasocketdescriptorif((listenfd=socket(AF_return-1;,0))</*Eliminates"Addressalreadyinuse"errorfrombind.*/if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,(constvoid*)&optval,sizeof(int))<return-...EchoServer:open_listenfd/*ListenfdwillbeanendpointforallrequeststoportonanyIPaddressforthishost*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);serveraddr.sin_port=htons((unsignedshort)port);if(bind(listenfd,(SA*)&serveraddr,sizeof(serveraddr))return-/*Makeitalisteningsocketreadytoacceptconnectionrequests*/if(listen(listenfd,LISTENQ)<0)return-1;return}EchoServer:socketcreatesasocketdescriptoronthe :indicatesthatthesocketisassociatedwith SOCK_STREAM:selectsareliablebytestreamconnectionintintlistenfd;/*listeningsocketdescriptor/*Createasocketdescriptorif((listenfd=socket(AF_ ,SOCK_STREAM,0))<0)return-1;EchoServer:Thesocketcanbegivensome/*Eliminates"Addressalreadyinuse"errorfrombind().*/if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,(constvoid*)&optval,sizeof(int))<return- HandytrickthatallowsustoreruntheserverimmediayafterwekillitOtherwisewewouldhavetowaitabout15Eliminates“Addressalreadyinuse”errorfromStronglysuggestyoudothisforallyourserverstosimplifyEchoServer:(initializesocketInitializesocketwithserverportAcceptconnectionfromanyIPstructstructsockaddr_inserveraddr;/*server'ssocketaddr/*listenfdwillbeanendpointforallrequeststoportonanyIPaddressforthishost*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ serveraddr.sin_port=htons((unsignedshort)port);serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);IPaddrandportstored work(big-endian)byte ADD00000000
EchoServer:bindassociatesthesocketwiththesocketaddresswejustintlistenfd; /*listeningsocket*/structintlistenfd; /*listeningsocket*/structsockaddr_inserveraddr;/*server’ssocketaddr*//*listenfdwillbeanendpointforallrequeststoportonanyIPaddressforthishost*/if(bind(listenfd,(SA*)&serveraddr,sizeof(serveraddr))<0)return-1;EchoServer:listenindicatesthatthissocketwillacceptconnection(connect)requestsfrom LISTENQisconst dicatinghowmanypendingrequestsintintlistenfd;/*listeningsocket/*Makeitalisteningsocketreadytoacceptconnectionrequests*/if(listen(listenfd,LISTENQ)<0)return-1;returnlistenfd;}We’refinallyreadytoenterthemainserverloopthatacceptsandprocessesconnectionrequests.EchoServer:MainTheserverloopsendlessly,waitingforconnectionrequests,thenreadinginputfromthe,andechoingtheinputbacktothe.main()/*createandconfigurethelisteningsocket*/準備工作就緒:socket,open_listenfd,bindaddress+port#while(1){}Accept():waitforaconnectionrequestecho():readandechoinputlinesfrom tilEOF*/Close():closetheconnection*/}OverviewoftheSockets Server /
requestfromnextEchoServer:accept()blockswaitingforaconnectionintintlistenfd;/*listeningdescriptor*/intconnfd;/*connecteddescriptor*/structsockaddr_lientaddr;intlen=connfd=Accept(listenfd,(SA acceptreturnsaconnecteddescriptor(connfd)withthesamepropertiesasthelisteningdescriptorReturnswhentheconnectionbetweenandserveriscreatedandreadyforI/OtransfersAllI/Owiththewillbedoneviatheconnectedacceptalso lient’sIPEchoServer:accept
Serverblocksinaccept,waitingforconnectionrequestonlisteningdescriptor
makesconnectionrequestbycallingandblocking connfdServerreturnsconnfd returnsfromConnectionisnowestablishedfdandConnectedvs.ListeningListeningdescriptor一直存在=服務(wù)器時Endpoint CreatedonceandexistsforlifetimeoftheEndpointoftheconnection andAnewdescriptoriscreatedeachtimetheserveracceptsaconnectionrequestfromaExistsonlyaslongasittakestoWhythe tion?AllowsforconcurrentserversthatcancommunicateoversimultaneouslyE.g.,Eachtimewereceiveanewrequest,weforkachildtohandletherequestEchoServer:IdentifyingtheTheservercandetermhename,IPaddress,andportofthestructhost
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- Unit 3 Wrapping Up the Topic-Project 教學設(shè)計 2024-2025學年仁愛科普版英語七年級上冊
- 2糖到哪里去了(教學設(shè)計)-2023-2024學年一年級下冊科學冀人版
- 南方科技大學《環(huán)境資源法》2023-2024學年第二學期期末試卷
- 《7 校園綠化設(shè)計》(教學設(shè)計)-2023-2024學年六年級下冊綜合實踐活動粵教版
- 冀中職業(yè)學院《書法藝術(shù)與欣賞》2023-2024學年第二學期期末試卷
- 蘇州經(jīng)貿(mào)職業(yè)技術(shù)學院《安裝工程計量與計價》2023-2024學年第二學期期末試卷
- 教科版高中信息技術(shù)必修教學設(shè)計-5.1 音頻信息的采集與加工
- 四川化工職業(yè)技術(shù)學院《信號分析與處理C》2023-2024學年第二學期期末試卷
- 濮陽醫(yī)學高等專科學?!段⒉夹g(shù)基礎(chǔ)》2023-2024學年第二學期期末試卷
- 四川外國語大學成都學院《兒科護理學(實驗)》2023-2024學年第二學期期末試卷
- 濟南2024年山東濟南廣播電視臺招聘14人筆試歷年參考題庫附帶答案詳解
- 海洋氣候預測模型創(chuàng)新研究-深度研究
- 《客戶服務(wù)基礎(chǔ)》教案及課件項
- 2025《醫(yī)藥企業(yè)防范商業(yè)賄賂風險合規(guī)指引》解讀課件
- 2025年湖南工業(yè)職業(yè)技術(shù)學院高職單招職業(yè)技能測試近5年??及鎱⒖碱}庫含答案解析
- 2025年丹參原藥材項目可行性研究報告
- 物理(A版)-安徽省合肥一中(省十聯(lián)考)2024-2025學年度高二年級上學期期末測試試題和答案
- 公路工程節(jié)后復工安全教育
- 人教版初中歷史與社會七年級下冊 6.3.3向西開放的重要門戶-烏魯木齊 說課稿
- 綜合材料繪畫課程設(shè)計
- 數(shù)學史簡介課件
評論
0/150
提交評論