多核软件开发技术第三讲:网络编程技术_第1页
多核软件开发技术第三讲:网络编程技术_第2页
多核软件开发技术第三讲:网络编程技术_第3页
多核软件开发技术第三讲:网络编程技术_第4页
多核软件开发技术第三讲:网络编程技术_第5页
已阅读5页,还剩116页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

多核软件开发技术

第三讲:网络编程技术

北京大学二零零八年春季*致谢:感谢Intel对本课程项目的资助ContentInternetApplicationArchitecturalStylesIntroductiontoLinux/UnixNetworkingTCP/IPClient-ServerArchitectureandProgrammingInternetApplicationArchitecturalStylesInternetApplicationArchitecturalStyles(1)Whatisanapplicationarchitecturalstyle?Anapplicationarchitectureisaninstantiationofastyleofsomeapplications.Astylewhichisrelatedtosomearchitecturesshowssomecommonpatternswithinvariableapplicationsystems.So,astylecanbeabstractedfrom---computerarchitectures---networkarchitectures---webarchitectures---softwarearchitectures---…InternetApplicationArchitecturalStyles(2)InternetApplicationArchitecturalStylesAnsoftwaresystemcancontainoneorseveralapplicationarchitecturalstylesAarchitecturalstylecancontainoneorseveraldifferentapplicationarchitectures.Ofcourse,anapplicationarchitecturecanhaveoneorseveralimplementations.So,application

style

architecture

implementation

InternetApplicationArchitecturalStyles(3)WhydoweneedtoknowInternetapplicationarchitecturalstyle?---TherearemanykindsofInternetapplicationarchitectureswhichareneededindifferentspecifications.Considerusingbrowseroruseclient/server,evenpeer-to-peersoftware?---Simpleisbeautiful.Whenyoucanuseasimplearchitecturetosolveaproblem,justdoit.---Performance.Whenyouchooseanarchitecturalstyletosolveaproblem,youshouldconsidersuchaspects:

---latency?---throughput?---roundtrips?

InternetApplicationArchitecturalStyles(4)Client/Serverstyle

Commonlythereexistsa(orseveral)commoncommunicationprotocolbetweenaclientandaserverAservercanprovideoneormoreservices.Aclientcansendrequestsandgetserviceresponsesfromaserverorseveralservers.EmphasizesseparationofconcernsInternetApplicationArchitecturalStyles(5)Layered-Client-ServersystemAlayeredsystemisorganizedhierarchically,eachlayerprovidingservicestothelayeraboveitandusingservicesofthelayerbelowitArchitecturesbasedonlayered-client-serverarereferredtoastwo-tiered,three-tiered,ormulti-tieredarchitecturesintheinformationsystemsliteratureInternetApplicationArchitecturalStyles(6)RemoteSessionStyleEachclientinalimitedperiod,canaccessuseoneormoresessionobjectswhicharecreatedbytheserverandinitiatesbytheclienttogettheclientstateinformationTheserverkeepstheapplicationstatesinsomethinglikehashtablewithsessionobjectsSecurefortrackingaclient,forexamplee-shopping,notrequiredtostoreuserpasswordinformationattheclientside.flexible,interactive,easytoextendservicesServerneedmoreresourcestokeepthestatesofeachclientInternetApplicationArchitecturalStyles(7)RemoteDataAccess

ClientssendinformationtoservertomakeSQLstatements.ServercreatesDBqueryobjectsconnectingtoDBServerdealswiththeSQLrequests,thenusessomekindofDBdrivertoaccessthedatafromthedatabaseServersendsthestructuralresponsedatatotheclientsServermaintainsper-clientstateforjoins/transInternetApplicationArchitecturalStyles(8)Pipe-and-Filter

ApipeisaninterprocesscommunicationmechanismavailableonbothWindowsandLinux(andUNIX)WindowspipesdifferfromLinuxpipesinthatasinglehandle(analogoustoaLinuxfiledescriptor)supportsbi-directionalI/O.Linuxpipesreturntwofiledescriptorstoeffectbi-directionalI/OInternetApplicationArchitecturalStyles(9)DistributedObjectse.g.CORBAorDCOMComponentsinteractaspeersEmphasizesobjectmanagement,datahiding,statedistributionUsesbrokeredclient/serverornotusesbrokersInternetApplicationArchitecturalStyles(10)ReplicatedRepository(RR)

Systemsbasedonthereplicatedrepositorystyleimprovetheaccessibilityofdataandscalabilityofservicesbyhavingmorethanoneprocessprovidethesameservice.Thesedecentralizedserversinteracttoprovideclientstheillusionthatthereisjustone,centralizedservice.

InternetApplicationArchitecturalStyles(11)CacheAvariantofreplicatedrepositoryisfoundinthecachestyle:replicationoftheresultofanindividualrequestsuchthatitmaybereusedbylaterrequests.Thisformofreplicationismostoftenfoundincaseswherethepotentialdatasetfarexceedsthecapacityofanyoneclient,asintheWWWInternetApplicationArchitecturalStyles(12)MobileCodeStylesVirtualMachine(VM)RemoteEvaluation(REV)

Intheparadigmofremoteevaluation,acomputationalcomponentAhastheknow-howinordertoexecutethetask,butitlacksthenecessaryresources,whicharesuitedonadifferentsite.ThecomputationalcomponentAthereforesendstheknow-howtoacomputationalcomponentB,whichresidesonthesamesiteastheresources,neededtofulfillthetask.ThecomputationalcomponentBexecutesthetaskusingtheknow-howreceivedfromA.TheresultsofthetaskaredeliveredbacktoA.

RemoteEvaluation(REV)ComponentBComponentAResourcesKnow-howresultSiteASiteBContCodeonDemand(COD)

Inthecodeondemandparadigm,thecomputationalcomponentAhaslocalaccesstotheresources,butdoesnotknowhowtoexecutethetask.Thus,itcontactsacomputationalcomponentBonadifferentsite,whichprovidestheknow-how.ThecomponentAloadstheknow-howfromBandexecutesthetasklocally.CodeonDemand(COD)ComponentBComponentAResourcesrequestKnow-howSiteASiteBMobileAgent(MA)Themobileagentparadigmisappliedtoasimilarscenarioastheremoteevaluation,wheretheresourcesresideonadifferentsitethanthecomputationalcomponentA.TheideaofthemobileagentparadigmistosendtheentirecomputationalcomponentAtotheremotesiteandnotonlytheknow-how.Themobileagentparadigmdiffersfromtheremoteevaluationandthecodeondemandparadigmsconcerningthemovementofanexistingandrunningcomputationalcomponent.MobileAgent(MA)ComponentAComponentAResources迁移resultSiteASiteBWebArchitectureWebArchitecturalStyle(1)Webarchitecturalstyleinvolvesfivefundamentalelements.ResourcesProtocolsRepresentationsofaResourceConnectorsComponentsWebArchitecturalStyle(2)InternetResourcesAninternetresourcecanbeanythingthatis---Informationcanbepresented,suchastext,image---Servicecanbeprovided,suchasSMTPserver---People

Definition:WithintheInternet,anaccessiblefacilityorentitythatcontainsinformationorprovidesdata-processingcapabilities.Note:AnexampleofanInternetresourceisaWebserver.

WebArchitecturalStyle(3)RepresentationsofaResourceTheWebisdesignedtomanipulateandtransferrepresentationsofaresourceAsingleresourcemaybeassociatedwithmultiplerepresentations(contentnegotiation)Arepresentationisintheformofamediatype---providesinformationforthisresource---providepotentialstatetransitionsMostrepresentationscanbecachedWebArchitecturalStyle(4)InternetwebrelatedProtocolssuchas:HTTPprotocol,SSL,andsoon.

WebArchitecturalStyle(5)Connectors

ConnectorModernWebExamplesclientlibwww,libwww-perl

serverlibwww,ApacheAPI,NSAPIcachebrowsercacheresolverbind(DNSlookuplibrary)tunnelSOCKS,SSLafterHTTPCONNECTWebArchitecturalStyle(6)ComponentsComponentModernWebExamplesoriginserverApachehttpd,MicrosoftIISgatewaySquid,CGI,ReverseProxyproxyCERNProxy,NetscapeProxy,GauntletuseragentNetscapeNavigator,Lynx,MOMspiderNetworkApplicationSimpleclient-serverHandlemultiplerequestsClientandserveronthesameEthernetcommunicatingusingTCPClientandserverondifferentLANsconnectedthroughaWANIntroductiontoLinux/UnixNetworkingUnixTCP/IP’sLayersISO--DataFlowAmongLayersUDP-UserDatagramProtocolProcedure:TheapplicationwritesamessagetoaUDPsocket,whichisthenencapsulatedinaUDPdatagram,whichisthenfurtherencapsulatedasanIPdatagram,whichisthensenttoitsdestination.Features:lackofreliabilitynotbeautomaticallyretransmittedConnectionlessSometimeveryusefulUDPOutput发送缓冲区不存在所以这里用虚框表示TCPProtocolTransmissionControlProtocolConnectionorientationStreamsReliabledeliveryNetworkadaptationFlowcontrolFull-duplexTCPoperationswrappinghigherlevelapplicationdatainsegmentswrappingthesegmentsintoIPdatagrams

associatingportnumberswithparticularapplicationsassociatingasequencenumberwitheverybyteinthedatastreamexchangingspecialsegmentstostartupandclosedownadataflowbetweentwohostsusingacknowledgmentsandtimeoutstoensuretheintegrityofthedataflowTCPHeaderFormatSequenceNumberAcknowledgementnumberOptions(0ormore32-bitwords)ChecksumUrgentPointerWindowSizeHLFINSYNRSTPSHACKURGData32bitsSourcePortDestinationPortTCPConnectionEstablishmentHostAHostBSendSYNseq=xConnect()阻塞ReceiveSYNAccept()阻塞SendSYNseq=y;ACK=x+1receiveSYN+ACKConnect()返回SendACKy+1receiveACKAccept()返回TimeASYNoccupiesonebyteofthesequencenumberspace,theacknowledgmentnumberintheACKofeachSYNistheinitialsequencenumberplusone.Similarly,theACKofeachFINisthesequencenumberoftheFINplusone.TCPDataTransmissionSenderReceiverApplicaiton

writes512ReceiverBufferEmpty01k512512SEQ=0ACK=512WIN=512512SEQ=512Applicaiton

writes512FullACK=1024WIN=0ACK=1024WIN=512Application

reads512byteSendermay

sendupto512128SEQ=1024Senderisblocked512512TCPPortNumberTheserverusesaspecifiedportnumbertoidentifyaservice.Forexample:FTP(20,21port),TrivialFileTransferProtocol(TFTP)serversareassignedtheUDPportof69.这些端口是标准服务端口,当然用户也可以自己定义哪个端口是服务端口端口的一般使用范围(16bit):TheInternetAssignedNumbersAuthority(IANA)maintainsalistofportnumberassignments.Thewell-knownports:0through1023.Theregisteredports:1024through49151.ThesearenotcontrolledbytheIANA,buttheIANAregistersandliststheusesoftheseportsasaconveniencetothecommunity.Thedynamicorprivateports,49152through65535,ephemeralportsPortNumberAllocationofUnixSystemsSocketPairThesocketpairforaTCPconnectionisthefour-tuplethatdefinesthetwoendpointsoftheconnection:thelocalIPaddresslocalportforeignIPaddressandforeignport.AsocketpairuniquelyidentifieseveryTCPconnectiononanetworkTCPPortNumbersandConcurrentServersTCPserverwithapassiveopenonport21

ConnectionrequestfromclienttoserverConcurrentserverhaschildhandleclient

SecondclientconnectionwithsameserverIPv4HeaderIPv6HeaderTCP/IPClient-ServerArchitectureandProgramming

TCP/IPClient-ServerArchitectureandProgrammingIntroductiontoSocketSocketAPIsSimpleTCPProgrammingPart1:SocketIntroductionSocketIntroductionWhatissocket?IntroducedinBSD4.1UNIX,1981AsocketisanabstractrepresentationofacommunicationendpointAninterfacebetweenapplicationandnetworkUsually,asocketassociateswithanaddressandaportProtocolFamilyConstantsforsocketfunctionTherearedifferentkindsofprotocolfamiliesAF_UNIX,AF_LOCALLocalcommunicationAF_INETIPv4InternetprotocolsAF_INET6IPv6InternetprotocolsAF_ROUTERoutingSocketsAF_KEY KeySocketAF_IPXIPX-NovellprotocolsAF_NETLINKKerneluserinterfacedeviceAF_X25ITU-TX.25/ISO-8208protocolAF_AX25AmateurradioAX.25protocolAF_ATMPVCAccesstorawATMPVCsAF_APPLETALKAppletalk

AF_PACKETLowlevelpacketinterfaceClient-ServerClientServerrequestresponseConnection-orientedProtocolsocket()bind()listen()accept()socket()connect()write()read()write()read()Connectionestablishmentdata(request)data(reply)clientblocksuntilconnectionfromclientserverclose()close()ConnectionlessProtocolsocket()bind()recvfrom()sendto()socket()sendto()ServerClientblocksuntildatareceivedfromaclientprocessrequestdata(request)data(reply)recvfrom()BasicDataTypesint8_t signed8bitintuint8_t unsigned8bitintint16_t signed16bitintuint16_t unsigned16bitintint32_t signed32bitintuint32_t unsigned32bitintsa_family_t

addressfamilysocklen_t

lengthofstructin_addr_t

IPv4addressin_port_t IPportnumberThedatatypesaredifferentondifferentplatformsGenericSocketAddressStructure

struct

sockaddr{ uint8_t sa_len;

sa_family_t

sa_family; char sa_data[14]; };sa_family

specifiestheaddresstype.sa_data

specifiestheaddressvalueItisagenericaddressstructure.UsuallymostsocketAPIsacceptstruct

sockaddrpointerasoneoftheirparametersEveryspecialprotocolfamilyhasitsownsocketaddressstruct,suchassockaddr_inforIPV4struct

sockaddr_in(IPv4)struct

in_addr{

in_addr_t

s_addr;/*32-bitIPv4address*//*networkbyteordered*/ };struct

sockaddr_in{ uint8_t sin_len;/*8-bit*/

sa_family_t sin_family;/*8-bit*/ in_port_t sin_port;/*16-bit*/

struct

in_addr

sin_addr;/*32-bit*/ char sin_zero[8];/*unused };sin_portisnetworkbyteordersin_addrisnetworkbyteorderItisusedonlyforIPV4sockaddrandsockaddr_insin_lensa_lensa_familysa_dataAF_INETsin_portsin_addrsin_zerosockaddrsockaddr_instructsockaddr_in6(IPv6)structin6_addr{uint8_ts6_addr[16];/*128-bitIPv6address*/};#defineSIN6_LENstructsockaddr_in6{uint8_tsin6_len;

sa_family_tsin6_family;in_port_tsin6_port;uin32_tsin6_flowinfo;

structin6_addrsin6_addr;};NetworkbyteordervsHostbyteorderNetworkbyteorderisabig-endianbyteorderHostbyteordercanbebig-endianorlittle-endianbyteorder0x11223344对于little-endian存放:11223344

地址由高-低SocketEndpointAddressThesocketAPIsaregeneric.Theremustbeagenericwaytospecifyendpointaddresses.TCP/IPrequiresanIPaddressandaportnumberforeachendpointaddress.Otherprotocolfamiliesmayuseotherschemes.Part2:SocketAPIs几个头文件说明<string.h>字符串处理函数定义头文件<sys/socket.h>socket相关函数定义头文件<netinet/in.h>Internet协议定义头文件,此头文件定义了如下结构:struct

sockaddr_insturct

in_addrin_addr_t并且定义了一些关于host和networkbyteorder的一些串换函数<netdb.h>定义了关于Internet数据库处理的函数,比如获得域名、IP地址等相关信息<arpa/inet.h>定义了一些网络地址和地址字符串转化的一些函数SomeUsefulAPIsDealingWithBinaryString#include<string.h>voidbzero(void*s,size_tn);voidbcopy(constvoid*src,void*dest,size_tn);int

bcmp(constvoid*s1,constvoid*s2,size_tn);void*memset(void*s,intc,size_tn);void*memcpy(void*dest,constvoid*src,size_tn);int

memcmp(constvoid*s1,constvoid*s2,size_tn);ByteOrderAPIs#include<netinet/in.h>uint32_thtonl(uint32_thostlong);convertstheunsignedintegerhostlongfromhostbyteordertonetworkbyteorderuint16_thtons(uint16_thostshort);convertstheunsignedshortintegerhostshortfromhostbyteordertonetworkbyteorderuint32_tntohl(uint32_tnetlong);convertstheunsignedintegernetlongfromnetworkbyteordertohostbyteorderuint16_tntohs(uint16_tnetshort);convertstheunsignedshortintegernetshortfromnetworkbyteordertohostbyteorderAddressConversionAPIs(1)#include<sys/socket.h>#include<netinet/in.h>#include<arpa/inet.h>

int

inet_aton(constchar*cp,struct

in_addr*inp);Thesecondparameterisnetworkbyteorder

char*inet_ntoa(struct

in_addrin);Thesecondparameterisnetworkbyteorder

in_addr_t

inet_addr(constchar*cp);Returnnetworkbyteorder最好不要使用这个函数AddressConversionAPIs(2)#include<sys/socket.h>#include<netinet/in.h>#include<arpa/inet.h>int

inet_pton(int

af,constchar*src,void*dst);Return1,ifok;0ifinputnotavalidformat;-1onerrorconstchar*inet_ntop(int

af,constvoid*src,char*dst,size_tcnt);ReturnpointertoresultorNULLonerrorAttention:pstandsforpresentnstandsfornumberThefirstargument:afAF_INETAF_INET6numericin_addr{}32bitbinaryIPv4addressDotted-decimalxxx.xxx.xxx.xxxpresentationinet_ptonInet_atoninet_ntopinet_ntoaHostnameHandlingAPIs#include<netdb.h>externint

h_errno;

struct

hostent*gethostbyname(constchar*name);#include<sys/socket.h>/*forAF_INET*/

struct

hostent*gethostbyaddr(constchar*addr,int

len,inttype);voidherror(constchar*s);constchar*hstrerror(interr);/*GNUextensions*/

int

gethostbyname_r(constchar*name,struct

hostent*ret,char*buf,size_tbuflen,struct

hostent**result,int*h_errnop);

intgethostbyname2_r(constchar*name,int

af,struct

hostent*ret,char*buf,size_tbuflen,struct

hostent**result,int*h_errnop);Itistimetowriteaprogram!#include<stdio.h>#include<unistd.h>int

main(int

argc,char*argv[]){charname[1024];

gethostname(name,sizeof(name));

printf("Thehostnameofthemachineis%s\n",name);return0;}Result:[root@localhostname]#./hostnameThehostnameofthemachineislocalhost.localdomainGettingtheIPAddressof#include<stdio.h>#include<sys/types.h>#include<errno.h>#include<sys/types.h>#include<netinet/in.h>#include<netdb.h>#include<arpa/inet.h>int

main(int

argc,char*argv[]){

struct

hostent*h;charip_str[INET_ADDRSTRLEN];constchar*p=NULL;if(argc!=2){

printf("Usage:hostip<domainname>\n");exit(1);}

if((h=gethostbyname(argv[1]))==NULL){

herror("gethostbyname");exit(1);}/*inet_ntop(),triestoconvertnumbericaddresstopresentationstring*/p=inet_ntop(AF_INET,((struct

in_addr*)h->h_addr),ip_str,INET_ADDRSTRLEN);if(p!=NULL){

printf("Hostnameis:%s\n",h->h_name);

printf("IPAddressis%s\n",ip_str);}else{

perror("inet_ntop");}return0;}struct

hostentstruct

hostent*hThehostentstructureisdefinedin<netdb.h>asfollows:struct

hostent{char*h_name;/*officialnameofhost*/char**h_aliases;/*aliaslist*/

int

h_addrtype;/*hostaddresstype*/

inth_length;/*lengthofaddress*/char**h_addr_list;/*listofaddresses*/}#defineh_addrh_addr_list[0]/*forbackwardcompatibility*/ContResult:[root@localhostname]#./hostip

Hostnameis:IPAddressis9DoeshaveonlyoneIP?

struct

hostent*h;char**hp;…hp=h->h_addr_list;/*Wecangettheipaddresslistinthisway:*/for(;*hp!=NULL;hp++){p=inet_ntop(AF_INET,(*(struct

in_addr**)hp),

ip_str,INET_ADDRSTRLEN);if(p!=NULL){

printf("Get

ip:%s\n",ip_str);}}…..

/*Wealsocangettheipaddresslistinanotherway:*/for(i=0;h->h_addr_list[i]!=NULL;i++){p=inet_ntop(AF_INET,((struct

in_addr*)h->h_addr_list[i]),

ip_str,INET_ADDRSTRLEN);if(p!=NULL){

printf("other

ip:%s\n",ip_str);}}

printf(“officedomainnameis%s\n",h->h_name);/*Wealsocangetthealiasdomainname:*/for(i=0;h->h_aliases[i]!=NULL;i++){

printf("aliasis%s\n",h->h_aliases[i]);}return0;}Result#./hostiplist

getip:9getip:9getip:9otherip:9otherip:9otherip:9officedomainnameisWhatistheprocedure?Howabout?[root@localhostname]#./hostiplist

getip:2otherip:2officedomainnameisaliasisOneIPcanhavemultipledomainnames!OnedomainnamecanhavemultipleIPaddresses!WhatIsTheProcedure?[root@localhostname]#nslookup

Note:nslookupisdeprecatedandmayberemovedfromfuturereleases.Considerusingthe`dig'or`host'programsinstead.Runnslookupwiththe`-sil[ent]'optiontopreventthismessagefromappearing.Server:51Address:51#53Non-authoritativeanswer:canonicalname=.Name:Address:2gethostbynamegetaddrbyhostLocalDNSserverapplicationcodeResolverconfigurationfile/etc/resolv.confOtherDNSserverProtocol:UDP:Port:53GivenanIP,howdoIgetahostdomain?#include<stdio.h>#include<sys/types.h>#include<string.h>#include<netdb.h>#include<netinet/in.h>#include<arpa/inet.h>#include<errno.h>int

main(int

argc,char*argv[]){

struct

hostent*h;

struct

in_addr

ip;if(argc!=2){

printf("Usage:hostdomain<ipaddress>\n");exit(1);}

/*getthenumericipaddressfrompresentationipaddressstring*/

if(inet_pton(AF_INET,argv[1],&ip)!=1){

perror("inet_pton");exit(1);}/*ok,itistimetocallgethostbyaddr()*/

if((h=gethostbyaddr((constchar*)&ip,sizeof(ip),AF_INET))==NULL){

herror("gethostbyname");exit(1);}

printf("domainnameis:%s\n",h->h_name);return0;}Result#./hostdomain2domainnameis:tulip.PKU.EDU.CNsocket()-createanendpointforcommunication#include<sys/types.h>#include<sys/socket.h>intsocket(intfamily,inttype,intprotocol)ArgumentFamily:AF_INETAF_INET6Type:SOCK_STREAMSOCK_DGRAMSOCK_RAWProtocol:0Returnvalue:-1isreturnedifanerroroccurs;otherwisethereturnvalueisadescriptorreferencingthesocket.Example--TCPint

sockfd;sockfd=socket( AF_INET, SOCK_STREAM, 0);if(sockfd<0){/*ERROR*/}bind()-bindanametoasocket

#include<sys/types.h>#include<sys/socket.h>

int

bind(int

sockfd,struct

sockaddr*my_addr,socklen_t

addrlen);Argument:

sockfd:socketdescriptorfromsocket()return

my_addr:localaddress

addrlen:lengthofmy_addr

Returnvalue:onsuccess,return0;errorreturn-1;errnoissetHowcanIknowthelocaladdress?HowcanyoufindoutwhatyourIPaddressissoyoucantellbind()?ThereisnorealisticwayforyoutoknowtherightIPaddresstogivebind()-whatifthecomputerhasmultiplenetworkinterfaces?Inserverside,ausercanuseINADDR_ANYtospecifytheIPaddressofserver.AndtheOScanallocateportautomatically,youcanusegetsockname()gettheportnumber.Forclient(tcporudp),thisassignsthesourceIPandportthatwillusedforIPdatagramssentonthesocket.bind()--SummaryProcessspecificationResultIPAddressportwildcard0KernelchoosesIPaddressandportwildcardnonzeroKernelchoosesIPaddress,ProcessspecifiesportLocalIPaddress0ProcessspecifiesIPaddress,kernelchoosesportLocalIPaddressnonzeroProcesschoosesIPaddress,processspecifiesportlisten()--listenforconnectionsonasocket#include<sys/socket.h>int

listen(ints,intbacklog);Argument:s:istheTCPsocket(alreadyboundtoanaddress)backlog:thenumberofincomingconnectionsthekernel shouldbeabletokeeptrackof.Returnvalue:onsuccess,return0;

Listen()returns-1,errnoissetOnlyusedinTCPserverprogramThetwoqueuesmaintainedbyTCPforalisteningsocketThelistenfunctionconvertsanunconnectedsocketintoapassivesocket,indicatingthatthekernelshouldacceptincomingconnectionrequestsdirectedtothissocket.MovesthesocketfromtheCLOSEDstatetotheLISTENstate.backlogThebacklogargumenttothelistenfunctionhashistoricallyspecifiedthemaximumvalueforthesumofbothqueues.Berkeley-derivedimplementationsaddafudgefactortothebacklog:Itismultipliedby1.5(p.257ofTCPv1andp.462ofTCPV2).Forexample,thecommonlyspecifiedbacklogof5reallyallowsupto8queuedentriesonthesesystems.Actualnumberofqueuedconnectionsforvaluesofbacklogaccept()--acceptaconnectiononasocket

#include<sys/types.h>#include<sys/socket.h>

int

accept(ints,struct

sockaddr*addr,socklen_t*addrlen);Arguments:socketdescriptthatisthepassivemodeTCPsocket

addr:isapointertoallocatedspace

addrlen:isavalue-resultargument,mustbesettothesizeofcliaddr,willbesetonreturntobethenumberofbytesincliaddrsetbythecalltoacceptReturnvalue:onsuccessreturnsanewsocketdescriptoror-1onerror,errnoissetacceptiscalledbyaTCPservertoreturnthenextcompletedconnectionfromthecompletedconnectionqueuewhichiscreatedbylistensystemcall.Afteracceptreturnsanewsocketdescriptor,I/Ocanbedoneusingtheread()andwrite()systemcalls.Ifnopendingconnectionsarepresentonthequeue,andthesocketisnotmarkedasnon-blocking,acceptblocksthecalleruntilaconnectionispresentIfthesocketismarkednon-blockingandnopendingconnectionsarepresentonthequeue,acceptreturnsEAGAIN.connect()--initiateaconnectiononasocket#include<sys/types.h>#include<sys/socket.h>int

connect(int

sockfd,conststruct

sockaddr*serv_addr,socklen_t

addrlen);Argument

sockfd:sockeddescriptor

serv_addr:containstheaddressoftheserver(IPAddressandTCPportnumber)

addrlen:serv_addrlengthReturnvalueOnsuccess,return0;otherwisereturn-1;errnoissetTheconnectfunctionisusedbyaTCPclienttoestablishaconnectionwithaTCPservertheconnectfunctioninitiatesTCP'sth

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论