多核軟件開(kāi)發(fā)技術(shù)第三講:網(wǎng)絡(luò)編程技術(shù)_第1頁(yè)
多核軟件開(kāi)發(fā)技術(shù)第三講:網(wǎng)絡(luò)編程技術(shù)_第2頁(yè)
多核軟件開(kāi)發(fā)技術(shù)第三講:網(wǎng)絡(luò)編程技術(shù)_第3頁(yè)
多核軟件開(kāi)發(fā)技術(shù)第三講:網(wǎng)絡(luò)編程技術(shù)_第4頁(yè)
多核軟件開(kāi)發(fā)技術(shù)第三講:網(wǎng)絡(luò)編程技術(shù)_第5頁(yè)
已閱讀5頁(yè),還剩116頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

多核軟件開(kāi)發(fā)技術(shù)

第三講:網(wǎng)絡(luò)編程技術(shù)

北京大學(xué)二零零八年春季*致謝:感謝Intel對(duì)本課程項(xiàng)目的資助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發(fā)送緩沖區(qū)不存在所以這里用虛框表示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.這些端口是標(biāo)準(zhǔn)服務(wù)端口,當(dāng)然用戶也可以自己定義哪個(gè)端口是服務(wù)端口端口的一般使用范圍(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對(duì)于little-endian存放:11223344

地址由高-低SocketEndpointAddressThesocketAPIsaregeneric.Theremustbeagenericwaytospecifyendpointaddresses.TCP/IPrequiresanIPaddressandaportnumberforeachendpointaddress.Otherprotocolfamiliesmayuseotherschemes.Part2:SocketAPIs幾個(gè)頭文件說(shuō)明<string.h>字符串處理函數(shù)定義頭文件<sys/socket.h>socket相關(guān)函數(shù)定義頭文件<netinet/in.h>Internet協(xié)議定義頭文件,此頭文件定義了如下結(jié)構(gòu):struct

sockaddr_insturct

in_addrin_addr_t并且定義了一些關(guān)于host和networkbyteorder的一些串換函數(shù)<netdb.h>定義了關(guān)于Internet數(shù)據(jù)庫(kù)處理的函數(shù),比如獲得域名、IP地址等相關(guān)信息<arpa/inet.h>定義了一些網(wǎng)絡(luò)地址和地址字符串轉(zhuǎn)化的一些函數(shù)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最好不要使用這個(gè)函數(shù)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;…h(huán)p=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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論