Вы находитесь на странице: 1из 28

VMCI Sockets Programming Guide

VMware Workstation 6.5 and VMware Server 2.0

VMCI Sockets Programming Guide

VMCI Sockets Programming Guide Item: EN-000054-00

You can find the most up-to-date technical documentation on our Web site at: http://www.vmware.com/support/ The VMware Web site also provides the latest product updates. If you have comments about this documentation, submit your feedback to: docfeedback@vmware.com

2008 VMware, Inc. All rights reserved. Protected by one or more U.S. Patent Nos. 6,397,242, 6,496,847, 6,704,925, 6,711,672, 6,725,289, 6,735,601, 6,785,886, 6,789,156, 6,795,966, 6,880,022, 6,944,699, 6,961,806, 6,961,941, 7,069,413, 7,082,598, 7,089,377, 7,111,086, 7,111,145, 7,117,481, 7,149,843, 7,155,558, 7,222,221, 7,260,815, 7,260,820, 7,269,683, 7,275,136, 7,277,998, 7,277,999, 7,278,030, 7,281,102, 7,290,253, 7,356,679, 7,409,487, 7,412,492, 7,412,702, 7,424,710, and 7,428, 636; patents pending. VMware, the VMware boxes logo and design, Virtual SMP and VMotion are registered trademarks or trademarks of VMware, Inc. in the United States and/or other jurisdictions. All other marks and names mentioned herein may be trademarks of their respective companies.

VMware, Inc. 3401 Hillview Ave. Palo Alto, CA 94304 www.vmware.com

VMware, Inc.

Contents

AboutThisBook

1 AboutVMCISockets 7
IntroducingVMCISockets 7 HowVMCISocketsWork 7 PossibleUseCases 8 Performance 8 PersistenceofSockets 8 SocketProgramming 8 FeaturesinSpecificReleases 8 LocationofIncludeFile 9 WebAccesswithStreamVMCISockets 9 NetworkStoragewithDatagramVMCISockets 10

2 PortingtoVMCISockets 11
PortingExistingSocketApplications 11 IncludeaNewHeaderFile 11 ChangeAF_INETtoVMCISockets 11 ObtaintheCID 11 TheVMCISock_GetLocalCID()Function 11 ConnectionOrientedStreamSocket 12 ConnectionlessDatagramSocket 12 InitializingtheAddressStructure 12 CommunicatingBetweenGuests 12 VMCISocketsandNetworking 12 SettingupaNetworklessGuest 12 CommunicatingBetweenGuestandHost 12

3 CreatingStreamVMCISockets 13
StreamVMCISockets 13 PreparingtheServerforaConnection 14 Socket()Function 14 SetandGetSocketOptions 14 Bind()Function 15 Listen()Function 15 Accept()Function 15 Select()Function 15 Recv()Function 16 Send()Function 16 Close()Function 16 Poll()Information 16 Read()andWrite() 16 Getsockname()Function 16 HavingtheClientRequestaConnection 17 Socket()Function 17 Connect()Function 17 Send()Function 17 Recv()Function 18
VMware, Inc. 3

VMCI Sockets Programming Guide

Close()Function 18 Poll()Information 18 Read()andWrite() 18

4 CreatingDatagramVMCISockets 19
DatagramVMCISockets 19 PreparingtheServerforaConnection 20 Socket()Function 20 SocketOptions 20 Bind()Function 20 Getsockname()Function 21 Recvfrom()Function 21 Sendto()Function 21 Close()Function 21 HavingtheClientRequestaConnection 21 Socket()Function 21 Sendto()Function 22 Connect()andSend() 22 Recvfrom()Function 22 Close()Function 22

A LearningMoreAboutSockets 23
AboutBerkeleySocketsandWinsock 23 ResourcesontheWeb 23 Wikipedia 23 Sockaddr 23 MSDN 23 LinuxManualPages 24 HardcopyBooks 24

Glossary Index 27

25

VMware, Inc.

About This Book

TheVMwareVMCISocketsProgrammingGuidedescribeshowtoprogramvirtualmachinecommunications interface(VMCI)sockets,anAPIthatfacilitatesfastandefficientcommunicationbetweenvirtualmachines.

Revision History
VMwarerevisesthisguidewitheachreleaseoftheproductorwhennecessary.Arevisedversioncancontain minorormajorchanges.Table 1summarizesthesignificantchangesineachversionofthisguide. Table 1. Revision History
Revision 20080327 20080620 20080815 Description Firstdraftofthismanualforpossibleinclusioninearlybetareleases. SeconddraftforVMwareWorkstation6.5Beta2andVMwareServer2.0RC1releases. Thirddraft,withsocketoptions,forVMwareWorkstation6.5RCrelease.

Intended Audience
ThisguideisintendedforprogrammerswhoaredevelopingapplicationswithVMCIsocketstocreateCor C++networkingapplicationsthattargetguestoperatingsystemsonVMwarehosts,orvirtualmachine communications.VMCIsocketsarebasedonTCPsockets.Chaptersinthisguideassumesthatyouarefamiliar witheitherBerkeleysocketsorWinsock,theWindowsimplementation.Ifyouarenotfamiliarwithsockets, Appendix Aprovidespointerstolearningresources.

Documentation Resources
ToaccessthecurrentversionsofVMwareAPIandSDKdocumentation,goto: http://www.vmware.com/support/pubs/sdk_pubs.html ToaccessthecurrentversionsofotherVMwaremanuals,goto: http://www.vmware.com/support/pubs

Documentation Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentation.Sendyourfeedbackto: docfeedback@vmware.com

VMware, Inc.

VMCI Sockets Programming Guide

Technical Support and Education Resources


Thefollowingsectionsdescribethetechnicalsupportandeducationalresourcesavailabletoyou.

Online Support
YoucansubmitquestionsorpostcommentstotheDeveloperCommunitySDKsandAPIsforum,whichis monitoredbyVMwaretechnicalsupportandproductteams.Toaccesstheforum,goto: http://communities.vmware.com/community/developer

Support Offerings
TofindouthowVMwaresupportofferingscanhelpmeetyourbusinessneeds,goto: http://www.vmware.com/support/services

VMware Professional Services


VMwareEducationServicescoursesofferextensivehandsonlabs,casestudyexamples,andcoursematerials designedtobeusedasonthejobreferencetools.Coursesareavailableonsite,intheclassroom,andlive online.Foronsitepilotprograms andimplementationbestpractices,VMwareConsultingServicesprovides offeringstohelpyouassess,plan,build,andmanageyourvirtualenvironment.Toaccessinformationabout educationclasses,certificationprograms,andconsultingservices,goto: http://www.vmware.com/services/

VMware, Inc.

About VMCI Sockets

ThischapterintroducesVMCIsockets,discussesreleasespecificfeatures,andillustratesseveralusecases. Topicsinclude: IntroducingVMCISocketsonpage 7 FeaturesinSpecificReleasesonpage 8 WebAccesswithStreamVMCISocketsonpage 9 NetworkStoragewithDatagramVMCISocketsonpage 10 ThisguideassumesthatyouknowabouteitherBerkeleysocketsorWinsock,theWindowsimplementation. Ifyouarenewtosockets,seeAppendix A,LearningMoreAboutSockets,onpage 23.

Introducing VMCI Sockets


TheVMwareVMCIsocketslibraryoffersanAPIthatissimilartotheBerkeleyUNIXsocketinterfaceandthe Windowssocketinterface,twoindustrystandards.VMCIsocketssupportfastandefficientcommunication betweenavirtualmachineanditshost,orbetweenguestvirtualmachinesonthesamehost. NOTETheoriginalVMCIlibrarywasreleasedasanexperimentalClanguageinterfacewithWorkstation6.0. ItincludedadatagramAPIandasharedmemoryAPI.Boththeseinterfaceshavebeendeprecated. Inthisrelease,thenewlibraryhasmoreflexiblealgorithms,wrappedinastreamsocketsinterfaceforexternal presentation.VMCIsocketsisafullysupportedinterface,notexperimental.

How VMCI Sockets Work


VMCIsocketsaresimilartoothersockettypes.LikeUNIX(local)sockets,VMCIsocketsworkonanindividual physicalmachine,andlikeUNIXsockets,theycanperforminterprocesscommunicationonthelocalsystem. BycontrastwithInternetsockets,communicatingprocessesusuallyresideondifferentsystemsacrossthe network.LikeInternetsockets,VMCIsocketsallowdifferentvirtualmachinestocommunicatewitheach other,providedtheyresideonthesameVMwarehost. TheVMCIsocketslibrarysupportsbothconnectionorientedstreamsocketslikeTCP,andconnectionless datagramsocketslikeUDP. VMCIsocketssupportdatatransferamongprocessesonthesamesystem(interprocesscommunication).They alsoallowcommunicationamongprocessesondifferentsystems,evenonesrunningdifferentversionsand typesofoperatingsystems.Inoneprotocolfamily,VMCIsocketscombinethebestaspectsofinterprocess communicationwiththeadvantagesofnetworkinginahostedvirtualenvironment. InVMCIsockets,avirtualsocketcanhaveonlytwoendpointsandtheservercannotinitiateaconnectionto theclient,unlikeTCPsockets. Socketsrequireactiveprocesses,socommunicatingguestvirtualmachinesmustberunning,notpoweredoff.

VMware, Inc.

VMCI Sockets Programming Guide

Possible Use Cases


VMCIsocketsofferthefollowing: Improvedintrahostperformanceforsocketmodifiedapplications Choiceofstreamordatagramcommunicationforoffthenetworkvirtualmachines Improvedprivacyofcommunicationsforhostedvirtualmachines Alternatedatapathforadministrativecontrolofguestvirtualmachines Improvedefficiencyfordatabasebackedapplicationsgoingguesttoguestfordata Abilitytoimplementahostguestfilesystem

Performance
EarlyperformancetestingindicatesthatVMCIsocketshavelowlatencyandhighthroughput.Socket endpointscommunicatewitheachotherat,orcloseto,thespeedofmemory. Becausecommunicationisonasinglephysicalsystem,VMCIsocketscanattainperformancecomparableto UNIXsockets,eventhoughtheyenablecommunicationacrossvirtualmachineslikeInternetsocketsdo. VMwaretailoreditsVMCIsocketsimplementationforhighperformance,especiallywithlargedatasets. VMwarerecommendsmessagesizeslargerthan512bytestofullyrealizetheperformancebenefits.VMCI socketshavehigherperformanceonanindividualphysicalmachinethanoverthewirenetworksockets.

Persistence of Sockets
VMCIsocketsconnectionsaredroppedaftersuspendandresumeofavirtualmachine. ConnectionscannotsurvivelivemigrationwithVMotionfromsourcetodestinationhost.

Socket Programming
Ifyouhaveexistingsocketbasedapplications,youneedtomakeonlyafewcodechangesforVMCIsockets. Ifyoudonothavesocketbasedapplications,youcaneasilyfindpublicdomaincodeontheWeb.Forexample, ApacheandFirefox,asshowninFigure 11,VMwareHostswithStreamVMCISocketsinGuests,onpage 9, usestreamsocketsandareopensource. RepurposinganynetworkingprogramtouseVMCIsocketsrequiresminimaleffort,becauseVMCIsockets behaveliketraditionalInternetsocketsonagivenplatform.However,somesocketoptionsdonotmakesense forcommunicationacrosstheVMCIdevice;suchoptionsaresilentlyignoredtoeaseprogramportability. Modificationisstraightforward,asdescribedinsectionPortingExistingSocketApplicationsonpage 11. Youincludeanewheaderfile.Beforethesocket()call,youcalltheVMCISock_GetAFValue()functionto returntheVMCIsocketsaddressfamilytoreplaceAF_INET.Youallocateareplacementsocketaddressing structure,sockaddr_vminsteadofsockaddr_in.OtherwiseVMCIsocketsusethesameAPIasBerkeley socketsorWindowssockets.

Features in Specific Releases


VMCIsocketscommunicatefromguesttoguest,orguesttohost,ononeVMwarehost.Theycanalsobeused forinterprocesscommunicationsonasingleguest.However,youcannotuseVMCIsocketsbetweenvirtual machinesrunningontwoseparatephysicalmachines,orfromonehosttoanotherhostacrossanetwork. IntheVMwareServer2.0andVMwareWorkstation6.5releases,streamsocketsarenotsupportedbetween hostandguest,soyoumustusedatagramsocketsinstead.Streamsocketsworkfromguesttoguestonly. Datagramsocketsworkfromguesttoguest,hosttoguest,andguesttohost. AsoftheVMwareServer2.0RC2andVMwareWorkstation6.5RCreleases,youcansettheminimum, maximum,anddefaultsizeofcommunicatingstreambuffers.SeeSetandGetSocketOptionsonpage 14.

VMware, Inc.

Chapter 1 About VMCI Sockets

Location of Include File


Youcanfindthevmci_sockets.hincludefileinthefollowingplaces: WindowsguestC:\Program Files\VMware\VMware Tools\VSock SDK\include Linuxguest/usr/lib/vmware-tools/include/vmci/ WindowshostC:\Program Files\VMware\VMware Workstation LinuxhostNotinstalledonthesystem.

Web Access with Stream VMCI Sockets


Figure 11showsanexampleoftwoVMwareWorkstationhosts,oneWindowsbasedandtheotherLinux based.Oneachhost,modifiedFirefoxbrowsersonWindowsandLinuxvirtualmachinesarecommunicating withamodifiedApacheserveronaseparatevirtualmachinethroughVMCIsockets.Meanwhile,aWeb browseroneachhostiscommunicatingwithaWebserverontheotherhostusingstandardnetworking throughTCP/IPsockets. VMwaredoesnotprovidemodifiedversionsofanythirdpartyapplicationsshownhere.However, opensourceversionsofFirefoxandApacheareavailable,soVMCIsocketsmodificationisfeasible. Figure 1-1. VMware Hosts with Stream VMCI Sockets in Guests
Windows host Windows Apache vsocklib.dll Linux host Linux Apache

Windows Firefox vsocklib.dll

Linux Firefox

Windows Firefox vsocklib.dll

Linux Firefox

VMCI socket VMCI driver

VMCI socket VMCI driver

VMCI socket VMCI driver

VMCI socket VMCI driver

VMCI socket VMCI driver

VMCI socket VMCI driver

VMCI virtual device

VMCI virtual device

Web server TCP/IP

IE 7

Apache TCP/IP

Firefox

WhentheFirefoxbrowsersonLinuxandWindowsrequestaconnectiontotheApacheWebserver,theVMCI socketslayercreatesasocketendpointandestablishesaconnectionthroughtheVMCIdriverandvirtual device.TheVMCIsocketslayeronthesystemwithApachereceivestheconnectionandprovidesanaccepted socketthroughthesocketonwhichApachewaslistening. Meanwhile,unmodifiedWebbrowsersonthephysicalmachines(WindowshostandLinuxhost)aresending requeststoeachothersWebserversoverastandardTCP/IPnetworkconnection.Ifguestoperatingsystems neededtoaccesstheWeboutsidethephysicalmachine,theywouldhavetousedifferent(unmodified)Web browsers,orhaveafallbackcapabilityoutsideofVMCIsockets.

VMware, Inc.

VMCI Sockets Programming Guide

Network Storage with Datagram VMCI Sockets


Figure 12showsanexampleofaVMwarehostactingastheNFSserverforthehomedirectoriesofitsthree clients:aWindowsguestandtwoLinuxguests.NFSusesdatagramsocketsforfileI/O.TheNFScodeonthe VMwarehostmustbeslightlymodifiedtouseVMCIsocketsinsteadofUDPdatagrams. VMwaredoesnotprovidemodifiedversionsofanythirdpartyapplicationsshownhere.However,an opensourceversionofNFSisavailable,soVMCIsocketsmodificationisfeasible. Figure 1-2. VMware Host with Datagram VMCI Sockets for NFS in Guests
host Windows H:\Home vsocklib.dll Linux /home Linux /home

VMCI socket VMCI driver

VMCI socket VMCI driver

VMCI socket VMCI driver

VMCI virtual device

NFS modified for VMCI sockets disk disk

Programmersusestreamsocketsfortheirhighreliability,anddatagramsocketsforspeedandlowoverhead.

10

VMware, Inc.

Porting to VMCI Sockets

ThischaptersummarizeshowtoportexistingsocketapplicationstoVMCIsockets.Topicsinclude: PortingExistingSocketApplicationsonpage 11 CommunicatingBetweenGuestsonpage 12 CommunicatingBetweenGuestandHostonpage 12

Porting Existing Socket Applications


Modifyingexistingsocketimplementationsisstraightforward.Thischapterdescribesthelinesofcodeyou needtochange.

Include a New Header File


ToobtainthedefinitionsforVMCIsockets,includethevmci_sockets.hheaderfile.
#include "vmci_sockets.h"

Change AF_INET to VMCI Sockets


CallVMCISock_GetAFValue()toobtaintheVMCIaddressfamily.Declarestructuresockaddr_vminsteadof sockaddr_in.Inthesocket()call,replacetheAF_INETaddressfamilywiththeVMCIaddressfamily. Whentheclientcreatesaconnection,insteadofprovidinganIPaddresstochooseitsserver,theclientmust providethecontextID(CID)ofavirtualmachine.

Obtain the CID


Invirtualhardwareversion6(Workstation6.0.xreleases),theVMCIvirtualdeviceisnotpresentbydefault. Afteryouupgradeavirtualmachinesvirtualhardwaretoversion7,thefollowinglineappearsinthe.vmx configurationfile,andwhenthevirtualmachinepowerson,anewvmci0.idlinealsoappearsthere.
vmci0.present = "TRUE"

Invirtualhardwareversion7(Workstation6.5releases),theVMCIvirtualdeviceispresentbydefault.When youcreateanewvirtualmachine,the.vmxconfigurationfilecontainslinesspecifyingPCIslotnumberand theIDoftheVMCIdevice.Onthevmci0.idline,CIDisthenumberindoublequotes.


vmci0.pciSlotNumber = "36" vmci0.id = "1066538581"

The VMCISock_GetLocalCID() Function


Forconvenience,youcancalltheVMCISock_GetLocalCID()functiontoobtainthelocalsystemsCID.This functionworksonbothhostserverandguestvirtualmachines. TheVMwarehostusuallyhasCID=2.

VMware, Inc.

11

VMCI Sockets Programming Guide

Connection-Oriented Stream Socket


Toestablishastreamsocket,includethesedeclarationsandcalls,andreplaceAF_INETwithafVMCI,assetby VMCISock_GetAFValue().
int sockfd_stream; int afVMCI = VMCISock_GetAFValue(); if ((sockfd_stream = socket(afVMCI, SOCK_STREAM, 0)) == -1) { perror(Socket stream); }

Connectionless Datagram Socket


Toestablishadatagramsocket,includethesedeclarationsandcalls:
int sockfd_dgram; int afVMCI = VMCISock_GetAFValue(); if ((sockfd_dgram = socket(afVMCI, SOCK_DGRAM, 0)) == -1) { perror(Socket datagram); }

Initializing the Address Structure


Toinitializetheaddressstructurepassedtobind(),insertthesesourcecodestatements,wheresockaddr_vm forVMCIsocketsreplacessockaddr_infornetworksockets.
struct sockaddr_vm my_addr = {0}; my_addr.svm_family = afVMCI; my_addr.svm_cid = VMADDR_CID_ANY; my_addr.svm_port = VMADDR_PORT_ANY;

Thefirstlinedeclaresmy_addrasasockaddr_vmstructureandinitializesitwithzeroes.AF_INETreplaces afVMCI.BothVMADDR_CID_ANYandVMADDR_PORT_ANYarepredefinedsothatatruntime,theservercanfillin theappropriateCIDandportvaluesduringabindoperation.Theinitiatingsideoftheconnection,theclient, mustprovidetheCIDandport,insteadofVMADDR_CID_ANYandVMADDR_PORT_ANY.

Communicating Between Guests


Tocommunicatebetweentwoguestvirtualmachinesonthesamehost,youcanestablishaVMCIsockets connectionusingeithertheSOCK_STREAMortheSOCK_DGRAMsockettype.

VMCI Sockets and Networking


Iflimitednetworkaccessissufficientforavirtualmachine,youcouldreplaceTCPnetworkingwithVMCI sockets,therebysavingmemoryandprocessorbandwidthbydisablingthenetworkstack.Ifnetworkingis enabled,asittypicallyis,VMCIsocketscanstillmakesomeoperationsrunfaster.

Setting up a Networkless Guest


Youcaninstallavirtualmachinewithoutanynetworkingpackages,soitcannotconnecttothenetwork.The systemimageofanetworkfreeoperatingsystemislikelytobesmall,andisolationisasecurityadvantage,at theexpenseofconvenience.Installnetworkfreesystemsasanetworklessguest.AfteryouupgradeVMware Tools,youcanuseVMCIsocketstocommunicatewiththenetworklessguest. YoucreateanetworklessguestwiththeoptionDonotuseanetworkconnectioninWorkstationwizard. Alternatively,youcantransformanetworkcapableguestintoanetworklessguestbyremovingallitsvirtual networkingdevicesintheWorkstationUI.

Communicating Between Guest and Host


Tocommunicatebetweenaguestvirtualmachineandthehost,youcanestablishaVMCIsocketsconnection usingtheSOCK_DGRAMsockettype.

12

VMware, Inc.

Creating Stream VMCI Sockets

ThischapterdescribesthedetailsofcreatingVMCIsocketstoreplaceTCPstreamsockets,intwosections: PreparingtheServerforaConnectiononpage 14 HavingtheClientRequestaConnectiononpage 17

Stream VMCI Sockets


TheflowchartinFigure 31showshowtoestablishconnectionorientedsocketsontheserverandclient. Figure 3-1. Connection-Oriented Stream Sockets Server
socket()

bind()

listen()

Client

socket()

accept() context ID wait for client connection connect() select() establish connection

recv() transmit data loop send() reply to data close()

send()

recv()

close()

WithVMCIsocketsandTCPsockets,theserverwaitsfortheclienttoestablishaconnection.Afterconnecting, theserverandclientcommunicatethroughtheattachedsocket.InVMCIsockets,avirtualsocketcanhave onlytwoendpoints,andtheservercannotinitiateaconnectiontotheclient.InTCPsockets,morethantwo endpointsarepossible,thoughrare,andtheservercaninitiateconnections.Otherwise,theprotocolsare identical.

VMware, Inc.

13

VMCI Sockets Programming Guide

Preparing the Server for a Connection


Atthetopofyourapplication,includevmci_sockets.handdeclareaconstantforthesocketbuffersize.In theexamplebelow,BUFSIZEdefinesthesocketbuffersize.Thenumber4096isagoodchoiceforefficiencyon multipleplatforms.ItisnotbasedonthesizeofaTCPpacket,whichisusuallysmaller.
#include "vmci_sockets.h" #define BUFSIZE 4096

TocompileonWindows,youmustalsocalltheWinsockWSAStartup()function.
err = WSAStartup(versionRequested, &wsaData); if (err != 0) { printf(stderr, "Could not register with Winsock DLL.\n"); goto cleanup; }

ThisisnotnecessaryonnonWindowssystems.

Socket() Function
InaVMCIsocketsapplication,obtainthenewaddressfamily(domain)toreplaceAF_INET.
int afVMCI = VMCISock_GetAFValue(); if ((sockfd = socket(afVMCI, SOCK_STREAM, 0)) == -1) { perror("socket"); goto cleanup; }

VMCISock_GetAFValue()returnsadescriptorfortheVMCIsocketsaddressfamilyifavailable.

Set and Get Socket Options


VMCIsocketsallowsyoutosettheminimum,maximum,anddefaultsizeofcommunicatingstreambuffers. Namesforthethreeoptionsare: SO_VMCI_BUFFER_SIZEDefaultsizeofcommunicatingbuffers;65536bytesifnotset. SO_VMCI_BUFFER_MIN_SIZEMinimumsizeofcommunicatingbuffers;defaultsto128bytes. SO_VMCI_BUFFER_MAX_SIZEMaximumsizeofcommunicatingbuffers;defaultsto262144bytes. Tosetanewvalueforasocketoption,callthesetsockopt()function.Togetavalue,callgetsockopt(). Forexample,tohalvethesizeofthecommunicationsbuffersfrom65536to32768,andverifythatthesetting tookeffect,insertthefollowingcode:
uint64 setBuf = 32768, getBuf; /* reduce buffer to above size and check */ if (setsockopt(sockfd, afVMCI, SO_VMCI_BUFFER_SIZE, (void *)&setBuf, sizeof setBuf) == -1) { perror(setsockopt); goto close; } if (getsockopt(sockfd, afVMCI, SO_VMCI_BUFFER_SIZE, (void *)&getBuf, sizeof getBuf) == -1) { perror(getsockopt); goto close; } if (getBuf != setBuf) { printf(stderr, SO_VMCI_BUFFER_SIZE not set to size requested.\n); goto close; }

ParameterssetBufandgetBufmustbedeclared64bit,evenon32bitsystems. Tohaveaneffect,socketoptionsmustbesetbeforeestablishingaconnection.Thebuffersizeisnegotiated beforetheconnectionisestablishedandstaysconsistentuntiltheconnectionisclosed.Foraserversocket,set optionsbeforeanyclientestablishesaconnection.Tobesurethatthisappliestoallsockets,setoptionsbefore callinglisten().Foraclientsocket,setoptionsbeforecallingconnect().

14

VMware, Inc.

Chapter 3 Creating Stream VMCI Sockets

Bind() Function
Thisbind()callassociatesthestreamsocketwiththenetworksettingsinthesockaddr_vmstructure,instead ofthesockaddr_instructure.
struct sockaddr_vm my_addr = {0}; my_addr.svm_family = afVMCI; my_addr.svm_cid = VMADDR_CID_ANY; my_addr.svm_port = VMADDR_PORT_ANY; if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof my_addr) == -1) { perror("bind"); goto close; }

Thesockaddr_vmstructurecontainsanelementforthecontextID(CID),whichspecifiesthevirtualmachine. Fortheserver(listener),thiscouldbeanyconnectingvirtualmachine.BothVMADDR_CID_ANYand VMADDR_PORT_ANYarepredefinedsothatatbindorconnectiontime,theappropriateCIDandportnumber arefilledinfromtheclient.VMADDR_CID_ANYisreplacedwiththeCIDofthevirtualmachineand VMADDR_PORT_ANYprovidesanephemeralportfromthenonreservedrange(>=1024). Theclient(connector)canobtainitslocalCIDbycallingVMCISock_GetLocalCID(). Thebind()functionisthesameasforaregularTCPsocketsapplication.

Listen() Function
Thelisten()callpreparestoacceptincomingclientconnections.TheBACKLOGmacropredefinesthenumber ofincomingconnectionrequeststhatthesystemacceptsbeforerejectingnewones.Thisfunctionisthesame aslisten()inaregularTCPsocketsapplication.
if (listen(sockfd, BACKLOG) == -1) { perror("listen"); goto close; }

Accept() Function
Theaccept()callwaitsindefinitelyforanincomingconnectiontoarrive,creatinganewsocket(andstream descriptornewfd)whenitdoes.Thestructuretheir_addrgetsfilledwithconnectioninformation.
struct sockaddr_vm their_addr; if ((newfd = accept(sockfd, (struct sockaddr *) &their_addr, sizeof their_addr) == -1) { perror("accept"); goto close; }

Select() Function
Theselect()callenablesaprocesstowaitforeventsonmultiplefiledescriptorssimultaneously.This functionhibernates,wakinguptheprocesswhenaneventoccurs.Youcanspecifyatimeoutinsecondsor microseconds.Aftertimeout,thefunctionreturnszero.Youcanspecifytheread,write,andexceptionfile descriptorsasNULLiftheprogramcansafelyignorethem.
if ((select(nfds, &readfd, &writefds, &exceptfds, &timeout) == -1) { perror("select"); goto close; }

VMware, Inc.

15

VMCI Sockets Programming Guide

Recv() Function
Therecv()callreadsdatafromtheclientapplication.Theserverandclientcancommunicatethelengthof datatransmitted,ortheservercanterminateitsrecv()loopwhentheclientclosesitsconnection.
char recv_buf[BUFSIZE]; if ((numbytes = recv(sockfd, recv_buf, sizeof recv_buf, 0)) == -1) { perror("recv"); goto close; }

Send() Function
Thesend()callwritesdatatotheclientapplication.Serverandclientmustcommunicatethelengthofdata transmitted,oragreebeforehandonasize.Oftentheserversendsonlyflowcontrolinformationtotheclient.
char send_buf[BUFSIZE]; if ((numbytes = send(newfd, send_buf, sizeof send_buf, 0)) == -1) { perror("send"); goto close; }

Close() Function
Giventheoriginalsocketdescriptorobtainedfromthesocket()call,theclose()callclosesthesocketand terminatestheconnectionifitisstillopen.Someserverapplicationscloseimmediatelyafterreceivingclient data,whileotherswaitforadditionalconnections.TocompileonWindows,youmustcalltheWinsock closesocket()insteadofclose().
#ifdef _WIN32 return closesocket(sockfd); #else return close(sockfd); #endif

Theshutdown()functionislikeclose(),butshutsdowntheconnection.

Poll() Information
Notallsocketbasednetworkingprogramsusepoll(),butiftheydo,nochangesarerequired.Thepoll() functionislikeselect().SeeSelect()Functiononpage 15forrelatedinformation.

Read() and Write()


Theread()andwrite()socketcallsareprovidedforconvenience.Theyprovidethesamefunctionalityas recv()andsend().

Getsockname() Function
Thegetsockname()functionretrievesthelocaladdressassociatedwithasocket.
my_addr_size = sizeof my_addr; if (getsockname(sockfd, (struct sockaddr *) &my_addr, &my_addr_size) == -1) { perror("getsockname"); goto close; }

16

VMware, Inc.

Chapter 3 Creating Stream VMCI Sockets

Having the Client Request a Connection


Atthetopofyourapplication,includevmci_sockets.handdeclareaconstantforthesocketbuffersize.In theexamplebelow,BUFSIZEdefinesthesocketbuffersize.ItisnotbasedonthesizeofaTCPpacket.
#include "vmci_sockets.h" #define BUFSIZE 4096

TocompileonWindows,youmustcalltheWinsockWSAStartup()function.SeePreparingtheServerfora Connectiononpage 14forsamplecode.

Socket() Function
InaVMCIsocketsapplication,obtainthenewaddressfamily(domain)toreplaceAF_INET.
int afVMCI = VMCISock_GetAFValue(); if ((sockfd = socket(afVMCI, SOCK_STREAM, 0)) == -1) { perror("socket"); goto exit; }

VMCISock_GetAFValue()returnsadescriptorfortheVMCIsocketsaddressfamilyifavailable.

Connect() Function
Theconnect()callrequestsasocketconnectiontotheserverspecifiedbyCIDinthesockaddr_vmstructure, insteadofbytheIPaddressinthesockaddr_instructure.
struct sockaddr_vm their_addr = {0}; their_addr.svm_family = afVMCI; their_addr.svm_cid = VMCISock_GetLocalCID(); their_addr.svm_port = SERVER_PORT; if ((connect(sockfd, (struct sockaddr *) &their_addr, sizeof their_addr)) == -1) { perror("connect"); goto close; }

Thesockaddr_vmstructurecontainsanelementfortheCIDtospecifythevirtualmachine.Fortheclient makingaconnection,theVMCISock_GetLocalCID()functionreturnstheCIDofthevirtualmachine. Theportnumberisarbitrary,althoughserver(listener)andclient(connector)mustusethesamenumber, whichmustdesignateaportnotalreadyinuse.Onlyprivilegedprocessescanuseports<1024. Theconnect()callallowsyoutousesend()andrecv()functionsinsteadofsendto()andrecvfrom(). Theconnect()callisnotnecessaryfordatagramsockets.

Send() Function
Thesend()callwritesdatatotheserverapplication.Theclientandservercancommunicatethelengthofdata transmitted,ortheservercanterminateitsrecv()loopwhentheclientclosesitsconnection.
char send_buf[BUFSIZE]; /* Initialize send_buf with your data. */ if ((numbytes = send(sockfd, send_buf, sizeof send_buf, 0)) == -1) { perror("send"); goto close; }

VMware, Inc.

17

VMCI Sockets Programming Guide

Recv() Function
Therecv()callreadsdatafromtheserverapplication.Sometimestheserversendsflowcontrolinformation, sotheclientmustbepreparedtoreceiveit.Usethesamesocketdescriptorasforsend().
char recv_buf[BUFSIZE]; if ((numbytes = recv(sockfd, recv_buf, sizeof recv_buf, 0)) == -1) { perror("recv"); goto close; }

Close() Function
Theclose()callshutsdownaconnection,giventheoriginalsocketdescriptorobtainedfromthesocket() function.TocompileonWindows,youmustcalltheWinsockclosesocket()insteadofclose().
#ifdef _WIN32 return closesocket(sockfd); #else return close(sockfd); #endif

Poll() Information
Notallsocketbasednetworkingprogramsusepoll(),butiftheydo,nochangesarerequired.

Read() and Write()


Theread()andwrite()socketcallsareprovidedforconvenience.Theyprovidethesamefunctionalityas recv()andsend().

18

VMware, Inc.

Creating Datagram VMCI Sockets

ThischapterdescribesthedetailsofcreatingVMCIsocketstoreplaceUDPsockets,intwosections: PreparingtheServerforaConnectiononpage 20 HavingtheClientRequestaConnectiononpage 21

Datagram VMCI Sockets


TheflowchartinFigure 41showshowtoestablishconnectionlesssocketsontheserverandclient. Figure 4-1. Connectionless Datagram Sockets Server
socket()

bind()

Client

socket()

recvfrom() context ID wait for client datagram sendto() transmit data loop sendto() reply to data close() close() recvfrom()

InUDPsockets,theserverwaitsfortheclienttotransmit,andacceptsdatagrams.InVMCIsockets,theserver andclientcommunicatesimilarlywithdatagrams.

VMware, Inc.

19

VMCI Sockets Programming Guide

Preparing the Server for a Connection


Atthetopofyourapplication,includevmci_sockets.handdeclareaconstantforthesocketbuffersize.In theexamplebelow,BUFSIZEdefinesthesocketbuffersize.Thenumber4096isagoodchoiceforefficiencyon multipleplatforms.ItisnotbasedonthesizeofaUDPdatagram.
#include "vmci_sockets.h" #define BUFSIZE 4096

TocompileonWindows,youmustcalltheWinsockWSAStartup()function.
err = WSAStartup(versionRequested, &wsaData); if (err != 0) { printf(stderr, "Could not register with Winsock DLL.\n"); goto exit; }

ThisisnotnecessaryonnonWindowssystems.

Socket() Function
ToalteraUDPsocketprogramforVMCIsockets,obtainthenewaddressfamilytoreplaceAF_INET.
int afVMCI = VMCISock_GetAFValue(); if ((sockfd_dgram = socket(afVMCI, SOCK_DGRAM, 0)) == -1) { perror("socket"); goto exit; }

VMCISock_GetAFValue()returnsadescriptorfortheVMCIsocketsaddressfamilyifavailable. Thiscallissimilartotheoneforstreamsockets,buthasSOCK_DGRAMinsteadofSOCK_STREAM.

Socket Options
CurrentlyVMCIsocketsoffersnooptionsfordatagramconnections.

Bind() Function
Thebind()callassociatesthedatagramsocketwiththenetworksettingsinthesockaddr_vmstructure, insteadofthesockaddr_instructure.
struct sockaddr_vm my_addr = {0}; my_addr.svm_family = afVMCI; my_addr.svm_cid = VMADDR_CID_ANY; my_addr.svm_port = VMADDR_PORT_ANY; if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof my_addr) == -1) { perror("bind"); goto close; }

Thesockaddr_vmstructurecontainsanelementforthecontextID(CID)tospecifythevirtualmachine.For theserver(listener),thiscouldbeanyconnectingvirtualmachine.VMADDR_CID_ANYandVMADDR_PORT_ANY arepredefinedsothatatbindorconnectiontime,theappropriateCIDandportnumberarefilledinfromthe client.VMADDR_CID_ANYisreplacedwiththeCIDofthevirtualmachineandVMADDR_PORT_ANYprovidesan ephemeralportfromthenonreservedrange(>=1024). Theclient(connector)canobtainitslocalCIDbycallingVMCISock_GetLocalCID(). TheVMCIsocketsbind()functionisthesameasforaUDPdatagramapplication.

20

VMware, Inc.

Chapter 4 Creating Datagram VMCI Sockets

Getsockname() Function
if (getsockname(sockfd, (struct sockaddr *) &my_addr, &svm_size) == -1) { perror("getsockname"); goto close; }

Thegetsockname()functionretrievesthelocaladdressassociatedwithasocket.

Recvfrom() Function
Therecvfrom()callreadsdatafromtheclientapplication.Serverandclientcancommunicatethelengthof datatransmitted,ortheservercanterminateitsrecvfrom()loopwhentheclientclosesitsconnection.
if ((numbytes = recvfrom(sockfd, buf, sizeof buf, 0, (struct sockaddr *) &their_addr, &svm_size)) == -1) { perror("recvfrom"); goto close; }

Sendto() Function
Thesendto()calloptionallywritesdatabacktotheclientapplication.SeeSendto()Functiononpage 22.

Close() Function
Theclose()callshutsdowntransmission,giventheoriginalsocketdescriptorobtainedfromthesocket() call.Someserverapplicationscloseimmediatelyafterreceivingclientdata,whileotherswaitforadditional connections.TocompileonWindows,youmustcalltheWinsockclosesocket()insteadofclose().
#ifdef _WIN32 return closesocket(sockfd); #else return close(sockfd); #endif

Having the Client Request a Connection


Atthetopofyourapplication,includevmci_sockets.handdeclareaconstantforbuffersize.Thisdoesnot havetobebasedonthesizeofaUDPdatagram.
#include "vmci_sockets.h" #define BUFSIZE 4096

TocompileonWindows,youmustcalltheWinsockWSAStartup()function.SeePreparingtheServerfora Connectiononpage 20forsamplecode.

Socket() Function
ToalteraUDPsocketprogramforVMCIsockets,obtainthenewaddressfamilytoreplaceAF_INET.
int afVMCI = VMCISock_GetAFValue(); if ((sockfd = socket(afVMCI, SOCK_DGRAM, 0)) == -1) { perror("socket"); goto exit; }

VMware, Inc.

21

VMCI Sockets Programming Guide

Sendto() Function
Becausethisisaconnectionlessprotocol,youpassthesocketaddressstructuretheir_addrasaparameterto thesendto()call.
struct sockaddr_vm their_addr = {0}; their_addr.svm_family = afVMCI; their_addr.svm_cid = SERVER_CID; their_addr.svm_port = SERVER_PORT; if ((numbytes = sendto(sockfd, buf, BUFIZE, 0, (struct sockaddr *) &their_addr, sizeof their_addr)) == -1) { perror("sendto"); goto close; }

Thesockaddr_vmstructurecontainsanelementfortheCIDtospecifythevirtualmachine.Fortheclient makingaconnection,theVMCISock_GetLocalCID()functionreturnstheCIDofthevirtualmachine. Theportnumberisarbitrary,althoughtheserver(listener)andclient(connector)mustusethesamenumber, whichmustdesignateaportnotalreadyinuse.Onlyprivilegedprocessescanuseports<1024.

Connect() and Send()


Evenwiththisconnectionlessprotocol,applicationscancalltheconnect()functiononcetosettheaddress, andcallthesend()functionrepeatedlywithouthavingtospecifythesendto()addresseachtime.
if ((connect(sockfd, (struct sockaddr *) &their_addr, sizeof their_addr)) == -1) { perror("connect"); goto close; } if ((numbytes = send(sockfd, send_buf, BUFSIZE, 0)) == -1) { perror("send"); goto close; }

Recvfrom() Function
Therecvfrom()calloptionallyreadsdatafromtheserverapplication.SeeRecvfrom()Functiononpage 21.

Close() Function
Theclose()callshutsdownaconnection,giventheoriginalsocketdescriptorobtainedfromthesocket() function.TocompileonWindows,calltheWinsockclosesocket(),asshowninClose()Functionon page 21.

22

VMware, Inc.

Learning More About Sockets

ThisappendixintroducesInternetsocketsandprovidespointerstofurtherinformation.

About Berkeley Sockets and Winsock


Asocketisacommunicationsendpointwithanameandaddressinanetwork.Socketsweremadefamousby theirimplementationinBerkeleyUNIX,andmadeuniversalbytheirincorporationintoWindows. Mostsocketbasedapplicationsemployaclientserverapproachtocommunications.Ratherthantryingto starttwonetworkapplicationssimultaneously,oneapplicationtriestomakeitselfalwaysavailable(theserver ortheprovider)whileanotherrequestsservicesasneeded(theclientortheconsumer). VMCIsocketsaredesignedtousetheclientserverapproachbut,unlikeTCPsockets,theydonotsupport multipleendpointssimultaneouslyinitiatingconnectionswithoneanother. Datagoingoverasocketcanbeinanyformat,andtravelineitherdirection. ManypeopleareconfusedbyAF_INETasopposedtoPF_INET.Linuxdefinesthemasidentical.Thismanual usesAFonly.AFmeansaddressfamily,whilePFmeansprotocolfamily.Asdesigned,asingleprotocolfamily couldsupportmultipleaddressfamilies.Howeverasimplemented,noprotocolfamilyeversupportedmore thanoneaddressfamily.ForInternetProtocolversion6(IPv6),AF_INET6issynonymouswithPF_INET6. WinSockincludesvirtuallyalloftheBerkeleysocketsAPI,aswellasadditionalWSAfunctionstocopewith cooperativemultitaskingandtheeventdrivenprogrammingmodelofWindows.

Resources on the Web


HereisasuccinctandcomprehensibleAPIexplanation: http://www.cas.mcmaster.ca/~qiao/courses/cs3mh3/tutorials/socket.html

Wikipedia
Hereisanoverviewofthehistoryanddesignofsockets: http://en.wikipedia.org/wiki/Berkeley_sockets

Sockaddr
HereisanoverviewofWinsockdesignandusage: http://www.sockaddr.com/TheSocketsParadigm.html

MSDN
HereisreferenceinformationaboutWinsock: http://msdn2.microsoft.com/enus/library/ms740673(VS.85).aspx

VMware, Inc.

23

VMCI Sockets Programming Guide

Linux Manual Pages


socket(7)TypemansocketonaLinuxsystem. http://www.yolinux.com/cgibin/man2html?cgi_command=socket(2) http://www.yolinux.com/cgibin/man2html?cgi_command=socket(7)

Hardcopy Books
InternetworkingwithTCP/IP,Volume3:ClientServerProgrammingandApplications,Linux/PosixSocketsVersion, byDouglasE.ComerandDavidL.Stevens,601pages,PrenticeHall,2000. UNIXNetworkProgramming,Volume1:TheSocketsNetworkingAPI,ThirdEdition,byW.RichardStevens(RIP), BillFenner,andAndrewM.Rudoff,1024pages,AddisonWesley,2003.

24

VMware, Inc.

Glossary

datagram Aselfcontainedunitofdatacontainingenoughinformationtoberoutedfromitssourcetoitsdestination withoutrelianceonearlierexchangesbetweensourceanddestinationhostsandthetransportingnetwork. IP InternetProtocol,thenetworklayeruponwhichTCPandUDParebased.DefinedbytheIETFinRFC791. IPisabesteffortpacketroutingprotocol.In2008,IPv4(version4)isnearlyuniversalbutIPv6(version6) deploymentsarebeginning.

socket Acommunicationsconnectionendpointwithanameandaddressinanetwork.Thetwoendpointsofa socketcanresideonthesamesystemorondifferentsystemsacrossthenetwork.Socketsaremostoften usedfornetworkapplications,buttheyarealsousefulforinterprocesscommunicationsonasingleserver. streamsocket Anetworkconnectionthatprovidesatwoway,sequenced,reliable,unduplicatedflowofdatawithout recordboundaries,withwelldefinedmechanismsforestablishingconnectionsanddetectingerrors.

TCP TransmissionControlProtocol,theInternetstandardforconnectionorientedstreamsockets.

UDP UserDatagramProtocol,theInternetstandardforconnectionlessdatagramsockets. VMCI Virtualmachinecommunicationinterface,asharedmemoryAPIanddatagraminterfacenowreplacedby VMCIsockets,astreamanddatagramsocketsinterface.

VMware, Inc.

25

VMCI Sockets Programming Guide

26

VMware, Inc.

Index

A
about VMCI sockets 7 accept() 15 address structure for sockets 12 AF_INET and PF_INET 23 AF_INET and VMCI sockets 11 afVMCI from VMCISock_GetAFValue() 12, 14, 15, 17

recvfrom() 21 release contents 8

S
select() 15 send() 16, 17 sendto() 21, 22 setsockopt() 14 SO_VMCI_BUFFER_SIZE 14 SOCK_DGRAM 12 SOCK_STREAM 12 socket() 8, 12, 14, 17, 20, 21 stream VMCI sockets 13

B
bind() 12, 15, 20 books about sockets 24

C
close() 16, 18, 21 connect() 17 connectionless socket 12 connection-oriented socket 12 context ID (CID) summary 11

T
technical support resources 6

U
use cases for VMCI sockets 8

D
datagram VMCI sockets 19

V
VMCI library deprecated 7 VMCISock_GetAFValue() 8, 14, 17, 20 VMCISock_GetLocalCID() 11, 15, 17, 20

G
getsockname() 16, 21 getsockopt() 14 guest to guest 8, 12 guest to host 8, 12

W
Web resources about sockets 23 write() 16, 18 WSAStartup() 14, 17, 20

H
hidden information about sockets 23 host to guest 8, 12

I
illustration of datagram VMCI sockets 10 illustration of stream VMCI sockets 9

L
listen() 15

P
PF_INET and AF_INET 23 poll() 16, 18 porting sockets applications 11

R
read() 16, 18 recv() 16, 18

VMware, Inc.

27

VMCI Sockets Programming Guide

28

VMware, Inc.

Вам также может понравиться