networking socket使用方法
Basicsocetprogramming
JensBandener∗(StudentElektro-andInformationstechnology)
May6,2010
Introduction
Thisshortskriptexplainsthebasicimplementationstepsforsocketbasednet-workcommunication.
Socketsareendpointsofbidirectionalinter-processornetworkcommunicationsusinganIPbasednetworkeitherforstreambasedorfordatagrambasedtrans-fers.Thesocketconnectioncanbeusedtotransferdataofanytypebetweenthetwoendpoints.Thesocketinterfaceisprovidedbytheoperatingsystem,whichmanagesthesocketsandtheconnection-information.
AttheEndofthisskriptyoufindaworkingexampleserver/clientapplicationshowingtheneccessarystepsforcommunicationbetweentheserverandtheclient.
∗Jens.Bandener@rub.de
with sequenzing andpacket transferContents
Introduction
2Socketcategories
2.1Communicationmodell........................3Socketprogramming
3.1Creatingsockets.......3.2Connectionestablishment..3.3Bindthesocket........3.4Server-side-listenandaccept3.5Sendingandreceivingdata.
....................................................................................................
123334555667
4Simpleserver-clientapplication
4.1clientside...............................4.2serverside...............................
2Socketcategories
TCPsocketsarestructuresdevelopedasusableinterfacesforimplementingnetworkconnectiontoapplications.Socketsareanindustrialstandardandimplementedinmanyprogramminglanguages.
Generally,aSocketisanfiledescriptorandcanbedevidedintotwomaincategories:(1)streamand(2)datagrammsockets.
Figure1:socketcategories
Thefirstcategory,stream,isusede.g.inTCPconnections.Streambasedsockedsprovidesequenzingandanerrorcorrection.Sequenzingmeans,thatthesocetconnectionguarantees,thateachsegmentofthefileisachievedinthesameorderitwassent.
2
processDatagrammbasedsockets,e.g.usedinUDPprotocols,arepackedorientedtransfers.Thisisaconnectionlesstransferinwhichthefileisdividedinpacketsbeforetransfering.Incontrasttothestreamtransfers,thedatagrammbasedtransfershavenoerrorcorrectionorsequenzing.
2.1Communicationmodell
Figure2:socetcommunication
Figure2showsthemainideainthesocketarchitecture.Insteadofprogram-mingthelowlevelnetworkcommunication,youcancreateasocket-connectionbetweentwoprocessesmanagedbytheoperatingsystem.Afterconnectingtwosocketsyoucanuseallstandartfunctionstoe.g.forwardfilesetc.tothesocet.Thesocketmanagestheremainingcommunicationprocess.Thisproceedingisverysimilartotheinterprocess-communicationintheunixsystem.
3
3.1
Socketprogramming
Creatingsockets
Socketscanbecreatedusingthesocket()command.Therequiredlibrariesforsocketprogrammingaresys/types.handthesys/socket.hlibrary.
Whencreatinganewsocketyouhavetospecifythefamily,thetypeandthedesiredprotocolforthesocket.
Listing1:creatinganewsocket
1
intsocket(intfamily,inttype,intprotocoll)
Thefirstparameterintfamiliyspecifiestheprotocolfamily.ThemostcommonprotocolistheAF_INETfortheTCP/IPcommunicationortheAF_UNIXforthelocalinterprocesscommunicationwithintheunix-system.Anextractofthepossiblefamiliesislistedintable1.
Thesecondparameterspecifiesthesockettype.Typicallyyouchoosebetweenstream-sockets(SOCK_STREAM)anddatagramm-sockets(SOCK_DGRAM).Thereareafewmoretypesforspecialuseswhicharenotannotatedatthispoint.
3
adress
AF_UNIX,AF_LOCAL
AF_INETAF_IPX
protocol
PF_UNIX,PF_LOCAL
PF_INETPF_IPX
meaning
localcommunication
IPv4internetcommunication(TCP/IP)
IPX-Novell-protocol
Table1:protocolfamilies,firstparameter
Thethirdandlastparameterallowsyoutochoosetheusedprotocol.Typicallythisparameterissetto0whichmeansthatthedefaultprotocolforthespecifiedsocked-typeisused.
3.2Connectionestablishment
Toconnecttwoprocesseswithalreadyimplementedsocketsyoucanusetheconnect()commandtoestablishtheconnection.
Listing2:connectingasocket
123
intconnect(
intsockfd,
structsockaddr∗addresssocklen_taddress_length);
Youneedtospecifythethreeparametersintheconnect()commandtoestablishtheconnection.Asintheexampleprogrammattheendofthisscript,theclienttypicallyconnectstoaserverapplicationn.Sotheconnect()commandwillbefoundintheclientapplication.
Thefistparametergivesthesocket,whichisusedfortheconnectiontotheserver.Thesecondparameterspecifiesthetheaddresstothedestinationsocket.Thisstructisspecifiedinthenetinet/in.hheaderfile.
Listing3:extractnetinet/in.h
1234567891011
#include unsignedshortintsin_family;unsignedshortintsin_port;structin_addrsin_addr; } structin_addr{ in_addr_ts_addr; }... Tomatchtherequiredtypesintheconnectcall,youneedtocastthesecondparametertostructsockaddr. 4 Listing4:connectingasocket 123 structsockaddr_inaddr; intconnect(socket,(structsockaddr∗)&addr, sizeof(addr)); Alternativetothecasttothesockaddryoucouldstraightusethestructsockaddr.Theadvantageofthesockaddr_inistheoptiontogivetheaddressandtheportseparatelyinsteadofgivingtheprotocolspecificaddress. 3.3Bindthesocket Afterconnectingthesocketyouneedto“bind”thesockettoaspecifiedport.Thecallforthebind()functionissimilartotheconnect()function. Listing5:bindfunction 123 intbind( intsockfd, structsockaddr∗addresssocklen_taddress_length); Incaseofasuccessfulbindthebind()functionreturns0,otherwiseitreturns−1forafailure. 3.4Server-side-listenandaccept Ontheoppositeside,heretheserverapplication,theserver-socketneedstolistenonthespecifiedportandpossiblyaccepttheincomingconnectionfromtheclientapplications.Typicallyitispossibletohandlemorethenoneincomingconnection.Forthiscasethesocketusesawaitingstacktohandletheincomingconnections. 1 intlisten(intsocket,intstack); Incomingconnectionscanbehandledbytheaccept()command. 123 intaccept( intsocket, structsockaddr∗address,socklen_t∗address_length); 3.5Sendingandreceivingdata Tosendorreceivedatayoucanusethecommonstandardfunctions.Whithwrite()youcansenddatatoasocketaswellalsread()receivesdatafromasocket. Listing6:send/receive 1 #include 5 2345 ssize_twrite(intsocket,constvoid∗data, size_tdata_length); ssize_tread(intsocket,void∗data, size_tdata_length);Aftertransmissioniscompleted,theclose()commandclosestheconnection. 12 #include intclose(intsocket); 4 4.1 Simpleserver-clientapplication clientside Thefollowinglistinggivesanexampleforaclientapplicationusingasocketfornetworkcommunication.Theapplicationconnectstoaserverandreceivesamessagefromtheserverside.Thereceivedmessagestringisprintedintheshellbeforetheconnectionisclosedontheclientside. Listing7:client.c 12345678910111213141516171819202122232425262728 #include#include#include#include#include#include#include#include #defineBUF1024 intmain(intargc,char∗∗argv){ intcreate_socket; char∗buffer=malloc(BUF);structsockaddr_inaddress;intsize; if(argc<2){ printf(\"input␣parameter␣incorrect\");exit(EXIT_FAILURE); } printf(\"creating␣socket...\"); if((create_socket=socket(AF_INET, SOCK_STREAM,0))>0) printf(\"Socket␣created!\\n\");address.sin_family=AF_INET; 6 293031323334353637383940414243444546 address.sin_port=htons(15000); inet_aton(argv[1],&address.sin_addr); if(connect(create_socket, (structsockaddr∗)&address,sizeof(address))==0) printf(\"connection␣established␣to␣%s...\", inet_ntoa(address.sin_addr)); size=recv(create_socket,buffer, BUF−1,0); if(size>0) buffer[size]=’\\0’; printf(\"\\n␣received:␣%s␣\\n\",buffer); close(create_socket);returnEXIT_SUCCESS; } 4.2serverside Ontheserversideasocketiscreatedandlisteningtoaspecifiedport.Whenaclientconnectstotheserverapplicationamessagestringissendtotheclient. Listing8:server.c 123456789101112131415161718192021222324 #include#include#include#include#include#include#include#include #defineBUF1024 intmain(void){ intcreate_socket,new_socket;socklen_taddrlen; char∗buffer=malloc(BUF);ssize_tsize; structsockaddr_inaddress;constinty=1; printf(\"creating␣server␣socket...\");if((create_socket= socket(AF_INET,SOCK_STREAM,0))>0)printf(\"socked␣created!\\n\"); 7 252627282930313233343536373839404142434445464748495051525354 setsockopt(create_socket,SOL_SOCKET, SO_REUSEADDR,&y,sizeof(int));address.sin_family=AF_INET; address.sin_addr.s_addr=INADDR_ANY;address.sin_port=htons(15000); if(bind(create_socket, (structsockaddr∗)&address,sizeof(address))!=0){ printf(\"ERROR...␣specified␣port␣in␣use␣\\n\"); } listen(create_socket,5); addrlen=sizeof(structsockaddr_in); while(1){ new_socket=accept(create_socket, (structsockaddr∗)&address,&addrlen);if(new_socket>0){ printf(\"client␣connected...\\n\"); } send(new_socket,\"−−>␣server␣message\", strlen(\"−−>␣server␣message\"),0); printf(\"message␣send␣to␣client...\\n\");close(new_socket); } close(create_socket);return0; } Tocompiletheapplicationsyoucanrunthegcccompilerwithoutanyspecialparameters. 12 gcc−oserverserver.cgcc−oclientclient.c Theeasiestwaytotesttheserverclientcommunicationistoopenaownterminalfortheserverandfortheclientseparately. Theserverapplicationmustbestartedfirst,sothattheporttowichtheclienttriestoconnectislistened.Inthefirstterminalruntheserverapplicationasfollowing: 12 ./server creatingserversocket...sockedcreated! Startingtheclientapplicationrequiresaremoteipaddresstoconnectto.Inthiscasetheserverandtheclientapplicationarerunningonthesamemachinesothatyoucanuse127.0.0.1asremoteip.Insteadofthisipyoucanuseanyotheriprepresentingmachinetheserverapplicationisrunningon. 8 12345 ./client127.0.0.1 creatingsocket...Socketcreated! connectionestablishedto127.0.0.1...received:−−>servermessage Whentheserversendsthemessagetotheclientsideastatusmessageispromtedontheserversideaswell. 12 clientconnected... messagesendtoclient... Thisexamplecanbeextendedtotransferanyothertypeofdatabetweenthetwosides. 9 References [WolfJ09]JürgenWolfLinux-Unix-Programmierung. 3.aktualisierteunderweiterteAuflageGalileo,2009,pp407-518ISBN-10:3836213664 10 因篇幅问题不能全部显示,请点此查看更多更全内容