Tải bản đầy đủ - 0 (trang)
Chapter 20. Send It Over the Net and Sock It to 'Em!

Chapter 20. Send It Over the Net and Sock It to 'Em!

Tải bản đầy đủ - 0trang

Chapter20.SendItOvertheNetand

SockItto'Em!



20.1.NetworkingandPerl

Becausesharinginformationandtransferringfilesamong

computersaresointegraltoeverythingwedo,Perloffersa

numberoffunctionstoobtainnetworkinformationinyour

program.Inordertowriteprogramsutilizinginterprocess

communication(sockets,messagequeues,etc.),itisessential

tounderstandsomeofthebasicterminologyassociatedwith

thenetwork.Thefollowingdiscussionismerelyanintroduction

tosomeofthecommonnetworkingvernacular,sothatwhen

youtrytodissectorwritePerlprogramsthatrequirethese

functions,youwillnothavetosearchthroughallyourCbooks

orwadethroughthemanualpagestofigureoutwhatisgoing

on.



20.2.Client/ServerModel

Wehaveseentheclient/servermodelinpreviouschapters

whenconnectingtoadatabaseandaWebserver.Mostnetwork

applicationsuseaclient/servermodel.Theserverprovides

someservicetooneormoreclients.Theclientmayrequesta

servicefromaserveronthesamemachineoronaremote

machine.Serverprogramsprovidesuchservicesase-mail,

Telnet,andFTP.Inorderfortheclientandservertotalktoeach

other,aconnectionismadebetweenthetwoprocesses,often

byutilizingsockets.Today,oneofthemostwell-known

client/servermodelsistheclient(browser)/server(Webserver)

modelusedbytheWeb.



20.3.NetworkProtocols(TCP/IP)

Whensendingdataoveranetwork,theremustbesomereliable

waytogetthedatafromonemachinetoanother.Inorderto

facilitatethiscomplicatedprocess,networksareorganizedina

seriesoflayers,eachlayerofferingaspecificnetworkingservice

tothenextlayer.Thelayersareindependentandhaveclearly

definedinterfacesforsupplyingfunctionstothenextlayer.A

highlayerpassesdataandinformationtothelayerbelowit,

untilthebottomlayerisreached.Atthebottomlayer,two

machinescanphysicallycommunicatewitheachother.The

rulesandproceduresusedforonenetworklayeronamachine

tocommunicatewithitscounterpartnetworklayeronanother

machinearecalledprotocols.Themostpopularsoftware

networkingprotocolsinUNIXareEthernet,IP,TCP,andUDP.



20.3.1.EthernetProtocol(Hardware)

TheEthernetlayeristhephysicallayerofthenetwork.Anyhost

connectedtotheEthernetbushasphysicalaccesstodatasent

overthenetwork.TheEthernetprotocolpreparesthedatafor

transmissionacrossawire.Itorganizesthedatainframes

using48-bitEthernetsourceanddestinationaddresses.The

Ethernetlayer,thelowestlayer,representsthetransferofdata

onthephysicalnetwork.



20.3.2.InternetProtocol(IP)

TheIPlayerisabovetheEthernetlayer;itpreparesthedatafor

routingonindependentnetworks.IPusesa4-byteInternet

protocoladdress(IPaddress),anddataisorganizedinpiecesof

informationcalledpackets.ApacketcontainsanIPheader

withsourceanddestinationaddresses,aprotocoltype,anda

dataportion.AlthoughtheIPprotocolismorecomplicatedthan

theEthernetprotocol,itisconnectionlessandunreliablein

deliveringpackets.Itdoesn'tguaranteehoworeventhatthe

datawillbereceived,butifthedatabeingsentistoolarge,IP

willbreakitdownintosmallerunits.TheIPprotocolhidesthe



underlyingdifferencesamongthedifferentnetworksfromthe

user.



20.3.3.TransmissionControlProtocol(TCP)

AlthoughtheIPlayerprovidessomeflowcontrol,itisnot

guaranteedtobereliable;thatis,thedatamaynotbereceived

inthesameorderitwassentoritmaynevergettoits

destinationatall.TheTCPprotocolprovidesareliableend-toendserviceandflowofcontrolanalogoustomakingaphone

call.Oncetheconnectionismade,bothsidescancommunicate

witheachother,andeveniftheytalkatthesametime,the

messagesarereceivedinthesameordertheyweresent.

ProgramsthatuseTCParerlogin,rsh,rcp,andtelnet.



20.3.4.UserDatagramProtocol(UDP)

UDPisanalternativetoTCP.Itisusedinapplicationsthatdo

notrequireacontinuousconnectionandaresendingshort

messagesperiodicallywithnoconcernwhethersomeofthe

dataislost.AUDPdatagramissimilartosendingaletterinthe

mail:Eachpackethasanaddress,thereisnoguaranteed

deliverytimeorsequencing,andduplicatepacketsmaybe

sent.[1]Thismethodpreventsprogramsfromhangingwhena

returnisexpected.Examplesofprogramsthatusethisprotocol

arerwhoandruptime.

[1]Rieken,B.,andWeiman,L.,AdventuresinUnix,NetworkApplications



Programming,JohnWiley&Sons,WileyProfessionalComputing:NewYork,

1992,p.7.



20.4.NetworkAddressing

Networksconsistofanumberofinterconnectedmachinescalled

hosts.Thesystemadministratorassignsthehostnamewhena

newmachineisaddedtothenetwork.Eachhostona

TCP/IP/Ethernetnetworkhasanameandthreetypesof

addresses:anEthernetaddress,anIPaddress,andaTCP

serviceportnumber.Wheninformationispassedfromonelayer

toanotherinanetwork,thepacketcontainsheader

information,includingtheaddressesneededtosendthepacket

toitsnextdestination.

Often,theaddressesreturnedbythenetworkingfunctionsare

inabinaryformat.Inordertoconvertthoseaddressesintoan

ASCIIformat,Perl'spackandunpackfunctioncanbeused.



20.4.1.EthernetAddresses

SincetheEthernetaddressisusuallyburnedintothePROM

whenthemachineismanufactured,itisnotanumberthatis

assignedbyasystemadministrator.Itissimplyusedtoidentify

thatparticularpieceofhardware.The/etc/ethers(UCB)file

containstheEthernetaddressesandhostnamesforaparticular

network.



20.4.2.IPAddresses

TheIPaddressisa32-bitnumberassignedbythesystem

administratortoaparticularhostonthenetwork.Ifahostis

connectedtomorethanonenetwork,itmusthaveanIP

addressforeachofthenetworks.Itconsistsofasetoffour

decimalnumbers(oftencalledafour-octetaddress)separated

bydots(e.g.,129.150.28.56).Thefirstpartoftheaddress

identifiesthenetworktowhichthehostisconnected,andthe

restoftheaddressrepresentsthehost.Theaddressesare

dividedintoclasses(AthroughC).Theclassesdetermine

exactlywhatpartoftheaddressbelongstothenetworkand

whatpartbelongstothehost.The/etc/hostsfilecontainsthe



addressofyourhostmachine,thehost'sname,andanyaliases

associatedwithit.(Seethegethostentandrelatedfunctionson

page792.)



20.4.3.PortNumbers

Whenservinganumberofuserprocesses,aservermayhavea

numberofclientsrequestingaparticularservicethatuseeither

theTCPorUDPprotocol.Whendeliveringinformationtoa

particularapplicationlayer,theseprotocolsusea16-bitinteger

portnumbertoidentifyaparticularprocessonagivenhost.

TCPandUDPportnumbersbetween0and255,calledwellknownports,arereservedforcommonservices.(Some

operatingsystemsreserveadditionalportsforprivileged

programs.)[2]ThemostcommonservicesareTelnetandFTP

withTCPportnumbers23and21,respectively.Ifyouwritea

serverapplicationthatwilluseeithertheTCPorUDPprotocols,

theapplicationmustbeassignedauniqueportnumber.This

portnumbershouldbesomenumberoutsidetherangeofthe

specialreservedportnumbers.The/etc/servicesfilecontainsa

listofthewell-knownportnumbers.

[2]Stevens,W.R.,andWright,G.R.,TCP/IPIllustrated,Volume1:The



Protocols,AddisonWesleyLongman,1993,p.13.



20.4.4.PerlProtocolFunctions

ThefollowingPerlfunctionsallowyoutoretrieveinformation

fromthe/etc/protocolsfile.Thefunctionsarenamedafterthe

systemcallsandlibraryfunctionsfoundinSections2and3of

theUNIXmanualpages.



ThegetprotoentFunction

Thegetprotoentfunctionreadsthenextlinefromthenetwork

protocolsdatabase,/etc/protocol,andreturnsalist.Theentries

aretheofficialnamesoftheprotocols;alistofaliases,or

alternativenames,fortheprotocol;andtheprotocolnumber.

Thesetprotoentfunctionopensandrewindsthe/etc/protocols



file.IfSTAYOPENisnonzero,thedatabasewillnotbeclosed

aftersuccessivecallstothegetprotoent.Theendprotoent

functionclosesthedatabase.



Format

getprotoent;

setprotoent(STAYOPEN);

endprotoent;

Example20.1.

(TheScript)

1while(($name,$aliases,$proto)=getprotent){

2printf"name=%-5s,aliases=%-6sproto=%-8s\n",

$name,$aliases,$proto;

}

(Output)

2name=ip,aliases=IPproto=0

name=icmp,aliases=ICMPproto=1

name=igmp,aliases=OGMPproto=2

name=ggp,aliases=GGPproto=3

name=tcp,aliases=TCPproto=6

name=pup,aliases=PUPproto=12

name=udp,aliases=IDPproto=17



Explanation

1. Thegetprotoentfunctiongetsanentryfromthe

/etc/protocolsfile.Theloopwillreadthroughthe

entirefile.Thenameoftheprotocol,anyaliases

associatedwithit,andtheprotocolnumberare

retrieved.

2. Eachentryanditsvaluesareprinted.



ThegetprotobynameFunction

Thegetprotobynamefunctionissimilartogetprotoentinthatit

getsanentryfromthe/etc/protocolsfile.getprotobyname

takestheprotocolnameasanargumentandreturnsitsname,

anyaliases,anditsprotocolnumber.



Format

getprotobyname(NAME);



Example20.2.



(TheScript)

1($name,$aliases,$proto)=getprotobyname('tcp');

print"name=$name\taliases=$aliases\t$protocolnumber=$pro

(Output)

name=tcpaliases=TCPprotocolnumber=6



Explanation

1. Thenameoftheprotocol,anyaliasname,andthe

protocolnumberareretrievedfromthe

/etc/protocolsfunction.Thenameoftheprotocol,

tcp,ispassedastheNAMEargument.



ThegetprotobynumberFunction

Thegetprotobynumberfunctionissimilartothegetprotoent

functioninthatitgetsanentryfromthe/etc/protocolsfile.The

getprotobynumbertakestheprotocolnumberasanargument

andreturnsthenameoftheprotocol,anyaliases,andits

protocolnumber.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 20. Send It Over the Net and Sock It to 'Em!

Tải bản đầy đủ ngay(0 tr)

×