Sunteți pe pagina 1din 32

VMCI Sockets Programming Guide

VMware ESXi 5.0 VMware Workstation 8.0

This document supports the version of each product listed and supports all subsequent versions until the document is replaced by a new edition. To check for more recent editions of this document, see http://www.vmware.com/support/pubs.

EN-000611-02

VMCI Sockets Programming Guide

You can find the most up-to-date technical documentation on the VMware 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

Copyright 20082011 VMware, Inc. All rights reserved. This product is protected by U.S. and international copyright and intellectual property laws. VMware products are covered by one or more patents listed at http://www.vmware.com/go/patents. VMware is a registered trademark or trademark 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
IntroductiontoVMCISockets 7 PreviousVMCIReleases 7 HowVMCISocketsWork 7 PersistenceofSockets 8 SocketProgramming 8 FeaturesinSpecificVMwareReleases 8 EnablingandFindingVMCISockets 8 EnablingVMCIBetweenVirtualMachines 8 LocationofIncludeFileforCPrograms 9 UseCasesforVMCISockets 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 CommunicatingBetweenHostandGuest 12 VMCISocketsandNetworking 12 SettingUpaNetworklessGuest 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
VMware, Inc. 3

VMCI Sockets Programming Guide

Recv()Function 18 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

5 SecurityoftheVMCIDevice 23
InterfacesforVMCISettings 23 VMCIDeviceAlwaysEnabled 23 VMCIandHardwareVersion 23 IsolationOptionsinVMX 24 Authentication 24 IsolationofVirtualMachines 24 IsolationinWorkstation 24 IsolationinESX/ESXi 25 IsolationofVMCISockets 25

Appendix:LearningMoreAboutSockets 27
AboutBerkeleySocketsandWinsock 27 TradePressBooks 27 BerkeleySockets 27 MicrosoftWinsock 28 ShortIntroductiontoSockets 28 SocketAddresses 28 Socket()SystemCall 28 Bind()SystemCall 28 Listen()SystemCall 29 Accept()SystemCall 29 Connect()SystemCall 29 SocketReadandWrite 30

Index 31

VMware, Inc.

About This Book

TheVMwareVMCISocketsProgrammingGuidedescribeshowtoprogramvirtualmachinecommunications interface(VMCI)sockets.TheVMCIsocketsAPIfacilitatesfastandefficientcommunicationbetweenguest virtualmachinesandtheirhost.

Revision History
VMwarerevisesthisguidewitheachreleaseoftheproductorwhennecessary.Arevisedversioncancontain minorormajorchanges.Table 1summarizesthesignificantchangesineachversionofthisguide. Table 1. Revision History
Revision 20120105 20110720 20100521 20091020 20090515 20080815 20080620 Description WindowsheaderfilenowinProgramFiles\CommonFiles\VMware\Drivers\vmci\sockets\include. ManualrevisedfortheWorkstation8.0releaseandfortheESXi5.0release. ManualrevisedfortheWorkstation7.1releaseandforESX/ESXi4.xreleases. ManualrevisedslightlyfortheWorkstation7.0release. Revisedmanual,includinghosttogueststreamsocketsupport,fortheESX/ESXi4.0release. Releasedmanual,withsocketoptions,forVMwareWorkstation6.5andVMwareServer2.0products. DraftofthismanualfortheVMwareWorkstation6.5Beta2andVMwareServer2.0RC1releases.

Intended Audience
ThismanualisintendedforprogrammerswhoaredevelopingapplicationsusingVMCIsocketstocreate C or C++networkingapplicationsforguestoperatingsystemsrunningonVMwarehosts.VMCIsocketsare basedonTCPsockets. ThisguideassumesthatyouarefamiliarwithBerkeleysocketsorWinsock,theWindowsimplementationof sockets.Ifyouarenotfamiliarwithsockets,Appendix:LearningMoreAboutSocketsonpage 27provides pointerstolearningresources.

Document Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentationandsearchtools.Sendyourfeedback todocfeedback@vmware.com.

VMware Technical Publications Glossary


VMwareTechnicalPublicationsprovidesaglossaryoftermsthatmightbeunfamiliartoyou.Fordefinitions oftermsastheyareusedinVMwaretechnicaldocumentationgotohttp://www.vmware.com/support/pubs.

VMware, Inc.

VMCI Sockets Programming Guide

Technical Support and Education Resources


Thefollowingsectionsdescribethetechnicalsupportresourcesavailabletoyou.Toaccessthecurrentversions ofotherVMwarebooks,gotohttp://www.vmware.com/support/pubs.

Online and Telephone Support


Touseonlinesupporttosubmittechnicalsupportrequests,viewyourproductandcontractinformation,and registeryourproducts,gotohttp://www.vmware.com/support.

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

VMware Professional Services


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

VMware, Inc.

About VMCI Sockets

Thischapterincludesthefollowingtopics:

IntroductiontoVMCISocketsonpage 7 FeaturesinSpecificVMwareReleasesonpage 8 EnablingandFindingVMCISocketsonpage 8 UseCasesforVMCISocketsonpage 9

ThisguideassumesthatyouknowabouteitherBerkeleysocketsorWinsock,theWindowsimplementation. Ifyouarenewtosockets,seeAppendix:LearningMoreAboutSocketsonpage 27.

Introduction to VMCI Sockets


TheVMwareVMCIsocketslibraryoffersanAPIthatissimilartotheBerkeleyUNIXsocketinterfaceandthe Windowssocketinterface,twoindustrystandards.VMCIsocketssupportfastandefficientcommunication betweenguestvirtualmachinesandtheirhost.

Previous VMCI Releases


TheoriginalVMCIlibrarywasreleasedasanexperimentalClanguageinterfacewithWorkstation6.0.VMCI includedadatagramAPIandasharedmemoryAPI.BoththeseinterfacesweredeprecatedinWorkstation6.5. TheVMCIsocketslibrarywasfirstreleasedwithWorkstation6.5andServer2.0asasupportedinterface.The VMCIsocketslibraryhadmoreflexiblealgorithms,wrappedinastreamsocketsAPIforexternalpresentation. StreamsocketsupportwasimprovedforESX/ESXihostswhenVMwarevSphere4andvCenterServer4 werereleased.

How VMCI Sockets Work


VMCIsocketsaresimilartoothersockettypes.LikelocalUNIXsockets,VMCIsocketsworkonanindividual physicalmachine,andcanperforminterprocesscommunicationonthelocalsystem.WithInternetsockets, communicatingprocessesusuallyresideondifferentsystemsacrossthenetwork.Similarly,VMCIsockets allowguestvirtualmachinestocommunicatethehostonwhichtheyreside. TheVMCIsocketslibrarysupportsbothconnectionorientedstreamsocketslikeTCP,andconnectionless datagramsocketslikeUDP.However,withVMCIsockets,avirtualsocketcanhaveonlytwoendpointsand unlikeTCPsockets,theservercannotinitiateaconnectiontotheclient. VMCIsocketssupportdatatransferamongprocessesonthesamesystem(interprocesscommunication).They alsoallowcommunicationtoprocessesondifferentsystems,includingonesrunningdifferentversionsand typesofoperatingsystems.VMCIsocketscompriseasingleprotocolfamily. Socketsrequireactiveprocesses,socommunicatingguestvirtualmachinesmustberunning,notpoweredoff. VMCIsocketsareavailableonlyattheuserlevel.KernelAPIsarenotsupported.

VMware, Inc.

VMCI Sockets Programming Guide

Persistence of Sockets
VMCIsocketsloseconnectionaftersuspendandresumeofavirtualmachine. InVMwarevSpherewithESX/ESXihostsandvCenterServer,VMCIsocketsdonotsurvivelivemigrationwith VMwarevMotionfromsourcetodestinationhost.InVMwarevSpherewithESX/ESXihosts,VMCIstream socketconnectionsaredroppedwhenavirtualmachineisputintofaulttolerance(FT)mode.NonewVMCI streamsocketconnectionscanbeestablishedwhileavirtualmachineisinFTmode.

Socket Programming
Ifyouhaveexistingsocketbasedapplications,onlyafewcodechangesarerequiredforVMCIsockets.Ifyou donothavesocketbasedapplications,youcaneasilyfindpublicdomaincodeontheWeb.Forexample, ApacheandFirefox,asshowninFigure 11,VMwareHostswithStreamVMCISocketsinGuests,onpage 9, usestreamsocketsandareopensource. RepurposinganetworkingprogramtouseVMCIsocketsrequiresminimaleffort,becauseVMCIsockets behaveliketraditionalInternetsocketsonagivenplatform.However,somesocketoptionsdonotmakesense forcommunicationacrosstheVMCIdevice,sotheyaresilentlyignoredtopromoteprogramportability. Modificationisstraightforward.Youincludeaheaderfile,changetheprotocoladdressfamily,andallocatea newdatastructure.OtherwiseVMCIsocketsusethesameAPIasBerkeleysocketsorWindowssockets.See PortingExistingSocketApplicationsonpage 11foradescriptionofthemodificationsneeded.

Features in Specific VMware Releases


VMCIsocketscommunicatebetweenhostandguest,orguesttoguest(deprecated),onaVMwarehost.You canuseVMCIsocketsforinterprocesscommunicationsonaguest.YoucannotuseVMCIsocketsbetween virtualmachinesrunningontwoseparatephysicalmachines,orfromonehosttoanotheracrossanetwork. IMPORTANTTouseVMCIsockets,virtualmachinesmustbeupgradedtoVMwarecompatibility7(virtual hardwareversion7),whichwasintroducedinVMwareWorkstation6.5andsupportedinESX/ESXi4.0. AsofVMwareServer2.0RC2andWorkstation6.5RCreleases,youcansettheminimum,maximum,and defaultsizeofcommunicatingstreambuffers.SeeSetandGetSocketOptionsonpage 14. ESX/ESXi4.x(vSphere4)releasesandlaterhavecompleteuserlevelsupportforVMCIsockets.Datagramand streamsocketsaresupportedbetweenhostandguestsonbothLinuxandWindows.IntheWorkstation7.x releasesrunningonWindowshosts,onlydatagramsocketsweresupported. IntheESXi5.0andWorkstation8.0releases,guesttoguestVMCIsocketsaredeprecated.Thefeaturewillbe removedinthenextmajorrelease.Otherwisefunctionalityissimilartothepreviousreleases.

Enabling and Finding VMCI Sockets


Forhosttoguestcommunication,VMCIisenabledonvirtualmachineswithversion7compatibilityandlater. Untilitisdeprecated,youcanenableguesttoguestcommunication.

Enabling VMCI Between Virtual Machines


IMPORTANTGuesttoguestcommunicationsaredeprecatedandwillberemovedinthenextmajorrelease. Fortwovirtualmachinestocommunicate,youmustenableVMCIonbothguestvirtualmachines,fromeither theuserinterfaceorthevSphereAPI.

ForVMwareWorkstation,selectVM>Settings>Options>GuestIsolation>EnableVMCI. ForESX/ESXiusingthevSphereClient,clicktheVMCIdevicepropertyEnableVMCIBetweenVMs. ThisisthesameassettingthevirtualmachineVMCIdevicetoallowUnrestrictedCommunication in thevSphereAPI.Thissettingtakeseffectwhenavirtualmachineisrestarted.

VMware, Inc.

Chapter 1 About VMCI Sockets

Location of Include File for C Programs


VMwareToolsoranotherinstallerplacesthevmci_sockets.hincludefileinoneofthefollowinglocations:

WindowsguestsonWorkstation8.0orlater,andWindowshostsofWorkstation8.0orlater C:\Program Files\Common Files\VMware\Drivers\vmci\sockets\include earlierWindowsguestsC:\ProgramFiles\VMware\VMwareTools\VSockSDK\include earlierWindowshostsC:\ProgramFiles\VMware\VMwareWorkstation Linuxguests/usr/lib/vmware-tools/include/vmci Linuxhosts/usr/lib/vmware/include/vmci ESX/ESXihostsNotinstalledonthesystem.

Use Cases for VMCI Sockets


VMCIsocketscanhelpwiththefollowingsolutions:

Implementnetworkbasedcommunicationforoffthenetworkvirtualmachines Improvetheprivacyofdatatransmissiononhostedvirtualmachines Increaseintrahostperformanceforsocketmodifiedapplications Provideanalternativedatapathformanagementofguestvirtualmachines Improveefficiencyofdatabasebackedapplicationsfromhosttoguest Implementafasthostguestfilesystem

Web Access with Stream VMCI Sockets


Figure 11showsanexampleoftwoVMwareWorkstationhosts,oneWindowsbasedandtheotherLinux based.Oneachhost,modifiedFirefoxbrowsersonWindowsandLinuxvirtualmachinesarecommunicating withamodifiedApacheserveronaseparatevirtualmachinethroughVMCIsockets.Meanwhile,aWeb browseroneachhostiscommunicatingwithaWebserverontheotherhostusingstandardnetworking throughTCP/IPsockets. VMwaredoesnotprovidemodifiedversionsofthethirdpartyapplicationsshowninthesediagrams. However,opensourceversionsofFirefoxandApacheareavailable. Figure 1-1. VMware Hosts with Stream VMCI Sockets in Guests
Windows Firefox vsocklib.dll Windows host Windows Apache vsocklib.dll Linux Firefox Windows Firefox vsocklib.dll Linux host Linux Apache 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

VMware, Inc.

VMCI Sockets Programming Guide

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

Network Storage with Datagram VMCI Sockets


Figure 12showsanexampleofaVMwarehostactingastheNFSserverforthehomedirectoriesofitsthree clients:aWindowsguestandtwoLinuxguests.NFSusesdatagramsocketsforfileI/O.TheNFScodeonthe VMwarehostmustbeslightlymodifiedtouseVMCIsocketsinsteadofUDPdatagrams. VMwaredoesnotprovidemodifiedversionsofthethirdpartyapplicationsshowninthesediagrams. However,anopensourceversionofNFSisavailable. 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

10

VMware, Inc.

Porting to VMCI Sockets

Thischapterincludesthefollowingtopics:

PortingExistingSocketApplicationsonpage 11 CommunicatingBetweenHostandGuestonpage 12

Porting Existing Socket Applications


Modifyingexistingsocketimplementationsisstraightforward.Thischapterdescribesthelinesofcodeyou mustchange.

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)ofavirtualmachineorhost.Anapplicationrunningonavirtualmachineuses thelocalcontextIDforbind()andaremotecontextIDforconnect().

Obtain the CID


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

Invirtualhardwareversion7(Workstation6.5releases),theVMCIvirtualdeviceispresentbydefault.When youcreateavirtualmachine,the.vmxconfigurationfilecontainslinesspecifyingPCIslotnumberandtheID oftheVMCIdevice.Onthevmci0.idline,CIDisthenumberindoublequotes.


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

The VMCISock_GetLocalCID() Function


Forconvenience,youcancalltheVMCISock_GetLocalCID()functiontoobtainthelocalsystemsCID.This functionworksonboththeESXihostandguestvirtualmachines,althoughtheESXihostalwayshasCID=2, eveninanestedvirtualmachine(VMrunninginaVM).

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 Host and Guest


Tocommunicatebetweenaguestvirtualmachineanditshost,establishaVMCIsocketsconnectionusingthe SOCK_DGRAMsockettype,oronproductplatformsthatsupportit(mostdo),theSOCK_STREAMsockettype.

VMCI Sockets and Networking


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

Setting Up a Networkless Guest


Youcaninstallavirtualmachinewithoutanynetworkingpackages,soitcannotconnecttothenetwork. The systemimageofanetworkfreeoperatingsystemislikelytobesmall,andisolationisasecurity advantage,attheexpenseofconvenience.Installnetworkfreesystemsasanetworklessguest.Afterinstalling VMwareTools,thehostcanuseVMCIsocketstocommunicatewiththenetworklessguest. YoucreateanetworklessguestwiththeoptionDonotuseanetworkconnectionintheWorkstationwizard. Alternatively,youcantransformanetworkcapableguestintoanetworklessguestbyremovingallitsvirtual networkingdevicesintheWorkstationUI.

12

VMware, Inc.

Creating Stream VMCI Sockets

ThischapterdescribesthedetailsofcreatingVMCIsocketstoreplaceTCPstreamsockets.

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. FortheclientthisisthelocalCID.Fortheserver(listener),thiscouldbeanyconnectingvirtualmachine.Both VMADDR_CID_ANYandVMADDR_PORT_ANYarepredefinedsothatatbindorconnectiontime,theappropriate CIDandportnumberarefilledinfromtheclient.VMADDR_CID_ANYisreplacedwiththeCIDofthevirtual machineandVMADDR_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; socklen_t their_addr_len = sizeof their_addr; if ((newfd = accept(sockfd, (struct sockaddr *) &their_addr, &their_addr_len)) == -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 = SERVER_CID; their_addr.svm_port = SERVER_PORT; if ((connect(sockfd, (struct sockaddr *) &their_addr, sizeof their_addr)) == -1) { perror("connect"); goto close; }

Thesockaddr_vmstructurecontainsanelementforthecontextID(CID)tospecifythevirtualmachineorhost. TheclientmakingaconnectionshouldprovidetheCIDofaremotevirtualmachineorhost. 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.

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 theclient(connector)thisisthelocalCID.Fortheserver(listener),itcouldbeanyconnectingvirtualmachine. VMADDR_CID_ANYandVMADDR_PORT_ANYarepredefinedsothatatbindorconnectiontime,theappropriate CIDandportnumberarefilledinfromtheclient.VMADDR_CID_ANYisreplacedwiththeCIDofthevirtual machineandVMADDR_PORT_ANYprovidesanephemeralportfromthenonreservedrange(>=1024). Theclient(connector)canobtainitslocalCIDbycallingVMCISock_GetLocalCID(). TheVMCIsocketsbind()functionisthesameasforaUDPdatagramapplication.

20

VMware, Inc.

Chapter 4 Creating Datagram VMCI Sockets

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; }

Recvfrom() Function
Therecvfrom()callreadsdatafromtheclientapplication.Serverandclientcancommunicatethelengthof datatransmitted,ortheservercanterminateitsrecvfrom()loopwhentheclientclosesitsconnection.
if ((numbytes = recvfrom(sockfd, buf, sizeof buf, 0, (struct sockaddr *) &their_addr, &my_addr_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.

Security of the VMCI Device

ThischapterprovidesbackgroundinformationaboutsecurityoftheVMCIdevice,especiallyaboutinterfaces thatarenotpartofthepublicVMCISocketsAPI.VMCISocketsareimplementedontopoftheVMCIdevice.

InterfacesforVMCISettingsonpage 23 VMCIDeviceAlwaysEnabledonpage 23 IsolationofVirtualMachinesonpage 24

Interfaces for VMCI Settings


VMCIisusedprimarilyforcommunicationbetweenvirtualmachinesandthehypervisor.Communication betweenvirtualmachinesiscontrolledbyasettinginavirtualmachinesVMXfile.VMwaresupportsenabling ordisablingoftherestrictedoption(unrestricted=false)bymeansofacheckboxintheUI. IMPORTANTGuesttoguestVMCIcommunicationsaredeprecatedintheESXi5.0release.Theywillcontinue toworkinESXi5.0updates,butwillberemovedinthenextESXirelease. To change the restricted setting in the vSphere Client

ClickEditSettings>Hardware>ShowAllDevices>VMCIdevice>EnableVMCIbetweenVMs.

To change the restricted setting in Workstation

ClickSettings>Options>GuestIsolation>EnableVMCI.

ForoldervirtualhardwareversionswithoutVMCI,thehypervisorrevertstoabackdoormechanismfor communication.HoweverVMwareservicesintroducedinnewproductsmayhavenobackdoorfallback,so someservicesmayrequireVMCItoworkcorrectly.

VMCI Device Always Enabled


TheVMCIdeviceisalwayspresentinrecentlycreatedVMwarevirtualmachines,raisingquestionsaboutthe securityimplicationsofhavingaVMCIdevice.

VMCI and Hardware Version


StartingwithVMwarevirtualhardwareversion7,theVMCIdeviceisenabledbydefault.Virtualmachines upgradedfromolderhardwareversionstoversion7acquiretheVMCIdeviceevenifitwasnotpresentbefore upgradingthevirtualhardware. TheVMCIdevicecannotberemoved.Onmostguestoperatingsystems,VMwareToolsshouldbeinstalledto provideaVMCIdevicedriver. Toaddresssecurityconcerns,VMwareprovidesamethodtorestricttheVMCIbasedservicesthatare availabletoavirtualmachine.Suchservicesarerestrictedtoatrustedsubsetofonlythehypervisorrelated servicesnecessarytorunavirtualmachineinisolation.Restrictedisthedefaultconfiguration.
VMware, Inc. 23

VMCI Sockets Programming Guide

Isolation Options in VMX


ESX/ESXi4.0andlaterprovidetwo.vmxoptionstocontrolVMCIisolation.
[vmci0.unrestricted = FALSE|TRUE]

Whenitsvmci0.unrestrictedoptionissetFALSE,avirtualmachinecanconnectonlytothehypervisor andtotrustedservicesonthehost,resultinginavirtualmachineisolatedfromothervirtualmachines. Whenitsvmci.unrestrictedoptionissetTRUE,avirtualmachinecancommunicatewithallhost endpointsand(untilfeatureremoval)othervirtualmachinesthathavevmci0.unrestrictedsetTRUE.


[vmci0.domain = <domainName>]

(ESX/ESXionly)Bydefault,allvirtualmachinesandhostapplicationsaremembersofthedefaultdomain ("")nullstring.Ifthevmci0.domainoptionspecifiesanondefaultdomain,thenthevirtualmachinecan communicateonlywiththehypervisorand(untilfeatureremoval)othervirtualmachinesinthesame domain.Thevirtualmachineisisolatedfromothervirtualmachineswithadifferentdomainname. Therestrictedoptionoverridesthedomainoption,soarestrictedvirtualmachinecannotcommunicatewith othervirtualmachineseveninthesamedomain. NOTEThepurposeoftheVMCIdomainistoorganizevirtualmachinesintogroupsthatcancommunicate witheachother,butnotwithvirtualmachinesoutsidethegroup.SinceguesttoguestVMCIcommunications aredeprecatedintheESXi5.0release,thedomainsettingwillcontinuetoworkinESXi5.0updates,butasof thenextESXirelease,thedomainsettingwillbeignored. Configuredforrestrictedcommunication,theVMCIdevicehasasecurityprofilesimilartoanyotherdevice suchaskeyboard,videomonitor,mouse,ormotherboard. Inunrestrictedmode,theVMCIdevicecancommunicatewithallothernonrestrictedVMCIdevicesonthe samehost,includinghostapplications.ThenatureoftheVMCIcommunicationdependsonthetypeofVMCI applicationsrunningonthehostssvirtualmachines.VMCIinitselfdoesnotexposeanyguestinformation.

Authentication
AllVMCIcommunicationsareauthenticated.Thesource(contextID)maynotbespoofed.TheVMCIfacility implicitlyauthenticatesanyhypervisorserviceasbeingpartofthetrustedcodebase.VMCIdoesnotprovide finegrainedauthenticationofcommunicationendpoints,soapplicationsmustdealwithfinegrained authenticationasaseparateissue.ItistheresponsibilityofapplicationsrunningontopofVMCItoimplement theirownauthenticationmechanismsifnecessary.VMCIensuresonlythatmalicioussoftwarecannotspoof thesourcefieldinVMCIdatagramsidentifyingthesendingvirtualmachine.

Isolation of Virtual Machines


ThissectiondescribesVMCIisolationmechanismsastheyapplytoVMwareWorkstationandESXihosts.

Isolation in Workstation
Whenavirtualmachineismarkedasisolated,itisonlyallowedto:

Interactwithhypervisorservices(contextID=0).ThisallowsuseofVMwareToolswithoutanyproblems evenforanisolatedvirtualmachine.

Avirtualmachinemarkedasisolatedisnotallowedto:

Interactwithothervirtualmachines.

Ifavirtualmachineisnotmarkedasisolateditcaninteractwiththehostand(untilfeatureremoval)other virtualmachines. Avirtualmachineisisolatedbydefault,butyoucanuseacheckboxintheUItoremoveitsisolation.

24

VMware, Inc.

Chapter 5 Security of the VMCI Device

Isolation in ESX/ESXi
ESX/ESXi4.0andlatersupporttheabilitytohaveseveralgroupsofvirtualmachinesperphysicalhost,where avirtualmachinecanseeonlythevirtualmachinesthatareamemberofthesamegroup.Thegroupsofvirtual machinesarenothierarchicalandmaynotoverlap. EachhostcanbelongtooneormoreVMCIdomains.AvirtualmachineassignedtoagivenVMCIdomaincan seeothervirtualmachineswithinthesamedomain,andthehypervisorcontext.BydefaultthereisoneVMCI domainperhost,andallvirtualmachinesarepartofthisdomain.ContextIDsmustbeuniqueacrossall domainsonahost.TheVMCIdomainsarespecifiedinthe.vmxfileofavirtualmachinenouserinterfaceis providedtomanageVMCIdomains. AnisolatedvirtualmachineislikeavirtualmachineinaVMCIdomainbyitself,withaccessonlytotrusted hypervisorservices. Ifavirtualmachineismarkedasisolated,ithasthesamerestrictionsaslistedaboveforWorkstation.

Isolation of VMCI Sockets


TheVMCIinterfacesdescribedabovearenotavailabletouserlevelprocesses.Instead,userlevelprocesses mustaccessVMCIthroughtheVMCISocketsAPI. AsofESX/ESXi4.1andWorkstation7.1,theVMCISocketsAPIpermitshostapplicationstocreatetrusted VMCISockets.AtrustedVMCIsocketcanbeusedforcommunicationwithisolatedvirtualmachines. The mechanismfordecidingwhetherahostapplicationcreatesatrustedVMCIsocketdependsonthehost operatingsystem:

LinuxAprocesswiththecapabilityCAP_NET_ADMINcreatestrustedendpoints. ESXiAuserworldwiththeaccessprivilegesdgram_vsocket_trustedorstream_vsocket_trusted createstrusteddatagramorstreamsockets,respectively. Creationoftrustedendpointsisnotcurrentlysupportedonotherhostoperatingsystems.

OnWorkstation8andFusion4,ahostapplicationrunningwiththesameuserIDasthevirtualmachineis consideredtrusted. TheVMCISocketsAPIalsosupportsthenotionofreservedports(portsnumbersunder1024),whereaprocess musthavecapabilityCAP_NET_BIND_SERVICEsoitcanbindtoaportwithinthereserved<1024portrange. OnWindows,onlymembersoftheAdministratorgroupareallowedtobindtoportsunder1024.

VMware, Inc.

25

VMCI Sockets Programming Guide

26

VMware, Inc.

Appendix: Learning More About Sockets

ThisappendixintroducesInternetsocketsandprovidespointerstofurtherinformation.

AboutBerkeleySocketsandWinsockonpage 27 ShortIntroductiontoSocketsonpage 28

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. Programmersusestreamsocketsfortheirhighreliability,anddatagramsocketsforspeedandlowoverhead.

Trade Press Books


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

Berkeley Sockets
WikipediaoffersanexcellentoverviewofthehistoryanddesignofBerkeleysockets. ForreferenceinformationaboutBerkeleysockets,locateaLinuxsystemwithmanualpagesinstalled,andtype mansocket.Youshouldbeabletofindbothsocket(2)andsocket(7)referencepages.

VMware, Inc.

27

VMCI Sockets Programming Guide

Microsoft Winsock
TheWinsockProgrammersFAQisanexcellentintroductiontoWindowssockets.Currentlyitishostedbythe http://tangentsoft.netWebsite. ForcompletereferenceinformationaboutWinsock,refertothepublicMSDNWebsite.

Short Introduction to Sockets


NetworkI/OissimilartofileI/O,althoughnetworkI/Orequiresnotonlyafiledescriptorsufficientfor identifyingafile,butalsosufficientinformationfornetworkcommunication. BerkeleysocketssupportbothUNIXdomainsockets(onthesamesystem)andInternetdomainsockets,also calledTCP/IP(transmissioncontrolprotocol)orUDP/IP(userdatagramprotocol).

Socket Addresses
Thesocketaddressspecifiesthecommunicationfamily.UNIXdomainsocketsaredefinedassockaddr_un. Internetdomainsocketsaredefinedassockaddr_inorsockaddr_in6forIPv6.
struct sockaddr_in short u_short struct in_addr char }; { sin_family; sin_port; sin_addr; sin_zero[8]; /* /* /* /* AF_INET */ port number */ Internet address */ unused */

Socket() System Call


Thesocket()systemcallcreatesoneendofthesocket.
int socket(int <family>, int <type>, int <protocol>);

Thefirstparameterspecifiesthecommunicationfamily,AF_UNIXorAF_INET. Thesecondparameterspecifiesthesockettype,SOCK_STREAMorSOCK_DGRAM. Thethirdparameterisusuallyzerobecausecommunicationfamiliesusuallyhaveonlyoneprotocol.

Thesocket()systemcallreturnsthesocketdescriptor,asmallintegerthatissimilartothefiledescriptorused inothersystemcalls.Forexample:
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int sockfd; sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

Bind() System Call


Thebind()systemcallassociatesanaddresswiththesocketdescriptor.
int bind(int sockfd, struct sockaddr *myaddr, int addrlen);

Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd. Thesecondparameterisapointertothesocketaddressstructure,whichisgeneralizedfordifferent protocols.Thesockaddrstructureisdefinedin<sys/socket.h>. Thethirdparameteristhelengthofthesockaddrstructure,becauseitcanvary.

28

VMware, Inc.

Appendix: Learning More About Sockets

InthesockaddrstructureforIPv4sockets,thefirstfieldspecifiesAF_INET.Thesecondfieldsin_portcan beanyinteger>5000.Lowerportnumbersarereservedforspecificservices.Thethirdfieldin_addristhe Internetaddressindottedquadnotation.Fortheserver,youcanusetheconstantINADDR_ANYtotellthe systemtoacceptaconnectiononanyInternetinterfaceforthesystem.Conversionfunctionshtons()and htonl()areforhardwareindependence.Forexample:


#define SERV_PORT 5432 struct sockaddr_in serv_addr; bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERV_PORT); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

Listen() System Call


Thelisten()systemcallpreparesaconnectionorientedservertoacceptclientconnections.
int listen(int sockfd, struct <backlog>);

Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd. Thesecondparameterspecifiesthenumberofrequeststhatthesystemqueuesbeforeitexecutesthe accept() systemcall.Higherandlowervaluesof<backlog>tradeoffhighefficiencyforlowlatency.

Forexample:
listen(sockfd, 5);

Accept() System Call


Theaccept()systemcallinitiatescommunicationsbetweenaconnectionorientedserverandtheclient.
int accept(int sockfd, struct sockaddr *cli_addr, int addrlen);

Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd. Thesecondparameteristheclientssockaddraddress,tobefilledin. Thethirdparameteristhelengthoftheclientssockaddrstructure.

Generallyprogramscallaccept()insideaninfiniteloop,forkinganewprocessforeachacceptedconnection. Afteraccept()returnswithclientaddress,theserverisreadytoacceptdata. Forexample:


for( ; ; ) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, sizeof(cli_addr)); if (fork() = 0) { close(sockfd); /* * read and write data over the network * (code missing) */ exit (0); } close(newsockfd); }

Connect() System Call


Ontheclient,theconnect()systemcallestablishesaconnectiontotheserver.
int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);

Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd. Thesecondparameteristheserverssockaddraddress,tobefilledin. Thethirdparameteristhelengthoftheserverssockaddrstructure.


29

VMware, Inc.

VMCI Sockets Programming Guide

Thisissimilartotheaccept()systemcall,exceptthattheclientdoesnothavetobindalocaladdresstothe socketdescriptorbeforecallingconnect().Theserveraddresspointedtobysrv_addrmustexist. Forexample:


#define SERV_PORT 5432 unsigned long inet_addr(char *ptr); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERV_PORT): serv_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR); connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

Socket Read and Write


SocketsusethesamereadandwritesystemcallsasforfileI/O.

Thefirstparameteristhesocketdescriptorfromthesocket()call,sockfd. Thesecondparameteristhereadorwritebuffer. Thethirdparameteristhenumberofbytestoread.

UnlikefileI/O,areadorwritesystemcallonastreamsocketmayresultinfewerbytesthanrequested.Itisthe programmersresponsibilitytoaccountforvaryingnumberofbytesreadorwrittenonthesocket. Forexample:


nleft = nbytes; while (nleft > 0) { if ((nread = read(sockfd, buf, nleft)) < 0) return(nread); /* error */ else if (nread == 0) break; /* EOF */ /* nread > 0. update nleft and buf pointer */ nleft - = nread; buf += nread; }

30

VMware, Inc.

Index

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

P
PF_INET and AF_INET 27 poll() 16, 18 port number, VMADDR_PORT_ANY 12, 15 porting sockets applications 11

R
read() 16, 18 recv() 16, 18 recvfrom() 21 release contents 8

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

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

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

D
datagram VMCI sockets 19

T
technical support resources 6

E
ESX/ESXi support for VMCI 8

U
use cases for VMCI sockets 9

F
Firefox and Apache VMCI sockets 9 flowchart of datagram sockets 19 flowchart of stream sockets 13

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

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

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

H
hidden information about sockets 27 host to guest and guest to guest 8, 12

L
listen() 15

N
NFS and datagram VMCI sockets 10

VMware, Inc.

31

VMCI Sockets Programming Guide

32

VMware, Inc.

S-ar putea să vă placă și