VMware ESXI ESXI 5.5, Workstation 9.0 User guide

  • Hello! I am an AI chatbot trained to assist you with the VMware ESXI ESXI 5.5 User guide. I’ve already reviewed the document and can help you find the information you need or explain it in simple terms. Just ask your questions, and providing more details will help me assist you more effectively!
VMCI Sockets Programming Guide
VMware ESXi 5.5
VMware Workstation 9.x
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-001166-00
VMware, Inc.
3401 Hillview Ave.
Palo Alto, CA 94304
www.vmware.com
2 VMware, Inc.
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 © 2008–2013 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. 3
Contents
AboutThisBook 5
1 AboutVMCISockets 7
IntroductiontoVMCISockets 7
PreviousVMCIReleases 7
HowVMCISocketsWork 7
PersistenceofSockets 8
SocketProgramming 8
FeaturesinSpecificVMwareReleases 8
EnablingandFindingVMCISockets 8
LocationofIncludeFileforCPrograms 8
SecurityofVMCISockets 9
UseCasesforVMCISockets 9
RabbitMQwithStreamVMCISockets 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
VMCI Sockets Programming Guide
4 VMware, Inc.
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
Authentication 23
IsolationOptionsinVMX 24
IsolationofVirtualMachines 24
IsolationinWorkstation 24
IsolationinESX/ESXi 24
TrustedVMCISockets 24
Appendix:LearningMoreAboutSockets 25
AboutBerkeleySocketsandWinsock 25
TradePressBooks 25
BerkeleySockets 25
MicrosoftWinsock 26
ShortIntroductiontoSockets 26
SocketAddresses 26
Socket()SystemCall 26
Bind()SystemCall 26
Listen()SystemCall 27
Accept()SystemCall 27
Connect()SystemCall 27
SocketReadandWrite 28
Index 29
VMware, Inc. 5
TheVMware®VMCISocketsProgrammingGuidedescribeshowtoprogramvirtualmachinecommunications
interface(VMCI)sockets.TheVMCIsocketsAPIfacilitatesfastandefficientcommunicationbetweenguest
virtualmachinesandtheirhost.
Revision History
VMwarerevisesthisguidewitheachreleaseoftheproductorwhennecessary.Arevisedversioncancontain
minorormajorchanges.Table 1summarizesthesignificantchangesineachversionofthisguide.
Intended Audience
ThismanualisintendedforprogrammerswhoaredevelopingapplicationsusingVMCIsocketstocreate
CorC++networkingapplicationsforguestoperatingsystemsrunningonVMwarehosts.VMCIsocketsare
basedonTCPsockets.
ThisguideassumesthatyouarefamiliarwithBerkeleysocketsorWinsock,theWindowsimplementationof
sockets.Ifyouarenotfa
miliarwithsockets,Appendix:LearningMoreAboutSocketsonpage 25provides
pointerstolearningresources.
Document Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentationandsearchtools.Sendyourfeedback
About This Book
Table 1. Revision History
Revision Description
20130830 ManualslightlyrevisedfortheESXi5.5release.
20120719 GuesttoguestcommunicationdedocumentedfortheESXi5.1release.
20120105 WindowsheaderfilenowinProgramFiles\CommonFiles\VMware\Drivers\vmci\sockets\include.
20110720 ManualrevisedfortheWorkstation8.0releaseandfortheESXi5.0release.
20100521 ManualrevisedfortheWorkstation7.1releaseandforESX/ESXi4.xreleases.
20091020 Manualrevisedsligh
tlyfortheWorkstation7.0release.
20090515 Revisedmanual,includinghosttogueststreamsocketsupport,fortheESX/ESXi4.0release.
20080815 Releasedmanual,withsocketoptions,forVMwareWorkstation6.5andVMwareServer2.0products.
20080620 DraftofthismanualfortheVMwareWorkstation6.5Beta2andVMwareServer2.0RC1releases.
VMCI Sockets Programming Guide
# VMware, Inc.
VMware Technical Publications Glossary
VMwareTechnicalPublicationsprovidesaglossaryoftermsthatmightbeunfamiliartoyou.Fordefinitions
oftermsastheyareusedinVMwaretechnicaldocumentationgotohttp://www.vmware.com/support/pubs.
VMware, Inc. 7
1
Thischapterincludesthefollowingtopics:
“IntroductiontoVMCISockets”onpage 7
“FeaturesinSpecificVMwareReleases”onpage 8
“EnablingandFindingVMCISockets”onpage 8
“UseCasesforVMCISockets”onpage 9
ThisguideassumesthatyouknowabouteitherBerkeleysocketsorWinsock,theWindowsimplementation.
Ifyouarenewtosockets,seeAppendix:LearningMoreAboutSockets”onpage 25.
Introduction to VMCI Sockets
TheVMwareVMCIsocketslibraryoffersanAPIthatissimilartotheBerkeleyUNIXsocketinterfaceandthe
Windowssocketinterface,twoindustrystandards.VMCIsocketssupportfastandefficientcommunication
betweenguestvirtualmachinesandtheirhost.
Previous VMCI Releases
TheoriginalVMCIlibrarywasreleasedasanexperimentalClanguageinterfacewithWorkstation6.0.VMCI
includedadatagramAPIandasharedmemoryAPI.BothinterfaceswerediscontinuedinWorkstation6.5.
TheVMCIsocketslibrarywasfirstreleasedwithWorkstation6.5andServer2.0asasupportedinterface.The
VMCIso
cketslibraryhadmoreflexiblealgorithms,wrappedinastreamsocketsAPIforexternalpresentation.
StreamsocketsupportwasimprovedforESX/ESXihostswhenVMwarevSphere™4andvCenter™Server4
werereleased.
How VMCI Sockets Work
VMCIsocketsaresimilartoothersockettypes.LikelocalUNIXsockets,VMCIsocketsworkonanindividual
physicalmachine,andcanperforminterprocesscommunicationonthelocalsystem.WithInternetsockets,
communicatingprocessesusuallyresideondifferentsystemsacrossthenetwork.Similarly,VMCIsockets
allowguestvirtualmachinestocommunicateth
ehostonwhichtheyreside.
TheVMCIsocketslibrarysupportsbothconnectionorientedstreamsocketslikeTCP,andconnectionless
datagramsocketslikeUDP.However,withVMCIsockets,avirtualsocketcanhaveonlytwoendpointsand
unlikeTCPsockets,theservercannotinitiateaconnectiontotheclient.
VMCIsocketssupportdatatransfe
ramongprocessesonthesamesystem(interprocesscommunication).They
alsoallowcommunicationtoprocessesondifferentsystems,includingonesrunningdifferentversionsand
typesofoperatingsystems.VMCIsocketscompriseasingleprotocolfamily.
Socketsrequireactiveprocesses,socommunicatingguestvirtualmachinesmustberunning,notpoweredoff.
VMCIsoc
ketsareavailableonlyattheuserlevel.KernelAPIsarenotsupported.
About VMCI Sockets
1
VMCI Sockets Programming Guide
8 VMware, Inc.
Persistence of Sockets
VMCIsocketsloseconnectionaftersuspendandresumeofavirtualmachine.
InVMwarevSpherewithESX/ESXihostsandvCenterServer,VMCIsocketsdonotsurvivelivemigrationwith
VMwarevMotion™fromsourcetodestinationhost.InVMwarevSpherewithESX/ESXihosts,VMCIstream
socketconnectionsaredroppedwhenavirtualmachineisputintofaulttolerance(F
T)mode.NonewVMCI
streamsocketconnectionscanbeestablishedwhileavirtualmachineisinFTmode.
Socket Programming
Ifyouhaveexistingsocketbasedapplications,onlyafewcodechangesarerequiredforVMCIsockets.Ifyou
donothavesocketbasedapplications,youcaneasilyfindpublicdomaincodeontheWeb.Forexample,
ApacheandFirefox,asshowninFigure 11,“ESXihostwithStreamVMCISocketsan
dRabbitMQ,”onpage 9,
usestreamsocketsandareopensource.
RepurposinganetworkingprogramtouseVMCIsocketsrequiresminimaleffort,becauseVMCIsockets
behaveliketraditionalInternetsocketsonagivenplatform.However,somesocketoptionsdonotmakesense
forcommunicationacrosstheVMCIdevice,sotheyaresi
lentlyignoredtopromoteprogramportability.
Modificationisstraightforward.Youincludeaheaderfile,changetheprotocoladdressfamily,andallocatea
newdatastructure.OtherwiseVMCIsocketsusethesameAPIasBerkeleysocketsorWindowssockets.See
“PortingExistingSocketApplications”onpage 11foradescriptionofthemodificationsneed
ed.
Features in Specific VMware Releases
VMCIsocketscommunicatebetweenthehostandaguestonVMwareplatformproducts.Youcouldalsouse
VMCIsocketsforinterprocesscommunicationsonaguest.YoucannotuseVMCIsocketsbetweenthehostand
avirtualmachinerunningonadifferenthost.
AsofVMwareServer2.0RC2andWorkstation6.5RCre
leases,youcansettheminimum,maximum,and
defaultsizeofcommunicatingstreambuffers.See“SetandGetSocketOptions”onpage 14.
ESX/ESXi4.x(vSphere4)releasesandlaterhavecompleteuserlevelsupportforVMCIsockets.Datagramand
streamsocketsaresupportedbetweenhostandguestsonbothLinuxandWi
ndows.IntheWorkstation7.x
releasesrunningonWindowshosts,onlydatagramsocketsweresupported.
IntheESXi5.0andWorkstation8.0releases,itwasannouncedthattheguesttoguestVMCIsocketsfeature
wouldbediscontinued.AsoftheESXi5.1release,onlyhosttoguestVMCIsock etsareallow
ed.
Enabling and Finding VMCI Sockets
Forhosttoguestcommunication,VMCIisenabledonvirtualmachineswithversion7compatibilityandlater.
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.
I
MPORTANTTouseVMCIsockets,virtualmachinesmustbeupgradedtoVMwarecompatibility7(virtual
hardwar eversion7),whichwasintroducedinVMwareWorkstation6.5andsupportedinESX/ESXi4.0.
VMware, Inc. 9
Chapter 1 About VMCI Sockets
Security of VMCI Sockets
VMCISocketsaremoresecureaftereliminationofguesttoguestcommunications.ForanoverviewofVMCI
security,seeChapter 5,“SecurityoftheVMCIDevice,”onpage 23.
Use Cases for VMCI Sockets
VMCIsocketscanhelpwiththefollowingsolutions:
Implementnetworkbasedcommunicationforoffthenetworkvirtualmachines
Improvetheprivacyofdatatransmissiononhostedvirtualmachines
Increasehostguestperformanceofsocketmodifiedapplicationsanddatabases
Implementafasthostguestfilesystem
Provideanalternativedatapathforaccesstoandmanagementofguestvirtualmachines
RabbitMQ with Stream VMCI Sockets
OntheESXihostinFigure 11,twovirtualmachinescontainamessagequeuingclientthatcommunicateswith
aguestproxythroughamqplib.GuestproxiescommunicatewiththehostproxyoverVMCISockets,which
treateachguestconnectionasaseparatesession.Thehostproxymultiplexesthesesessionsandcommunicates
withtheRabbitMQproxyov
erasingleTCP/IPsocket,passingencapsulatedAMQP.ARabbitMQnoderuns
onavirtualmachine.TheRabbitMQclusterisacollectionofRabbitMQnodesthatareassembledforreliability
andscaling.TheAMQPproxysplitsoutmultiplexedsessionsofindividualconnectionstoaRabbitMQnode.
Allthista
kesplaceonthemanagementnetwork,reducingtrafficontheguestnetwork.
Figure 1-1. ESXi host with Stream VMCI Sockets and RabbitMQ
Originatedin2003,AMQP(advancedmessagequeuingprotocol)isanindustrystandardforpassingbusiness
messagesbetweenapplicationsandorganizations.Itispopularinthebankingandfinanceindustries.
ESXi
Client
amqplib
Client
amqplib
VM
vmx
Guest
proxy
VMCI
Host
proxy
VMCI
Management network
Guest network
AMQP
AMQP
proxy
RabbitMQ
Cluster
Node
Node
Encapsulated
AMQP
RabbitMQ components
Middleware components
VM
vmx
Guest
proxy
VMCI Sockets Programming Guide
10 VMware, Inc.
RabbitMQsoftwareisanopensourcemessagebroker(ormessageorientedmiddleware)thatimplementsthe
AMQPstandard.SpringSourcecurrentlydevelopsandsupportsRabbitMQ.
Network Storage with Datagram VMCI Sockets
Figure 12showsanexampleofaVMwarehostactingastheNFSserverforthehomedirectoriesofitsthree
clients:aWindowsguestandtwoLinuxguests.NFSusesdatagramsocketsforfileI/O.TheNFScodeonthe
VMwarehostmustbeslightlymodifiedtouseVMCIsocketsinste
adofUDPdatagrams.
VMwaredoesnotprovidemodifiedversionsofthethirdpartyapplicationsshowninthesediagrams.
However,anopensourceversionofNFSisavailable.
Figure 1-2. VMware Host with Datagram VMCI Sockets for NFS in Guests
/home
Linux
VMCI socket
VMCI driver
/home
Linux
host
VMCI socket
VMCI driver
VMCI virtual device
NFS modified for VMCI sockets
H:\Home
Windows
vsocklib.dll
VMCI socket
VMCI driver
disk disk
VMware, Inc. 11
2
Thischapterincludesthefollowingtopics:
“PortingExistingSocketApplications”onpage 11
“CommunicatingBetweenHostandGuest”onpage 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)ofavi
rtualmachineorhost.Anapplicationrunningonavirtualmachineuses
thelocalcontextIDforbind()andaremotecontextIDforconnect().
Obtain the CID
Invirtualhardwareversion6(Workstation6.0.xreleases),theVMCIvirtualdeviceisnotpresentbydefault.
Afteryouupgradeavirtualmachine’svirtualhardwaretoversion7,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()functiontoobtainthelocalsystem’sCID.This
functionworksonboththeESXihostandguestvirtualmachines,althoughtheESXihostalwayshasCID=2,
eveninanestedvirtualmachine(VMrunninginaVM).
Porting to VMCI Sockets
2
VMCI Sockets Programming Guide
12 VMware, Inc.
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,
mustprovidetheCI
Dandport,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
VMw
areTools,thehostcanuseVMCIsocketstocommunicatewiththenetworklessguest.
Youcreateanetworklessguestwiththeoption“Donotuseanetworkconnection”intheWorkstationwizard.
Alternatively,youcantransformanetworkcapableguestintoanetworklessguestbyremovingallitsvirtual
networkingdevicesintheW
orkstationUI.
VMware, Inc. 13
3
ThischapterdescribesthedetailsofcreatingVMCIsocketstoreplaceTCPstreamsockets.
“PreparingtheServerforaConnection”onpage 14
“HavingtheClientRequestaConnection”onpage 17
Stream VMCI Sockets
TheflowchartinFigure 31showshowtoestablishconnectionorientedsocketsontheserverandclient.
Figure 3-1. Connection-Oriented Stream Sockets
WithVMCIsocketsandTCPsockets,theserverwaitsfortheclienttoestablishaconnection.Afterconnecting,
theserverandclientcommunicatethroughtheattachedsocket.InVMCIsockets,avirtualsocketcanha
ve
onlytwoendpoints,andtheserver cannotinitiateaconnectiontotheclient.InTCPsockets,morethantwo
endpointsarepossible,thoughrare,andtheservercaninitiateconnections.Otherwise,theprotocolsare
identical.
Creating Stream VMCI Sockets
3
socket()
bind()
listen()
accept()
Server
wait for client connection
send()
select()
recv()
connect()
establish connection
context ID
socket()
Client
recv() send()
close() close()
transmit data
reply to data
loop
VMCI Sockets Programming Guide
14 VMware, Inc.
Preparing the Server for a Connection
Atthetopofyourapplication,includevmci_sockets.handdeclareaconstantforthesocketbuffersize.In
theexamplebelow,BUFSIZEdefinesthesocketbuffersize.Thenumber4096isagoodchoiceforefficiencyon
multipleplatforms.ItisnotbasedonthesizeofaTCPpacket,whichisusu
allysmaller.
#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,insertthefollowingcod
e:
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
optionsbeforeanycl
ientestablishesaconnection.Tobesurethatthisappliestoallsockets,setoptionsbefore
callinglisten().Foraclientsocket,setoptionsbeforecallingconnect().
VMware, Inc. 15
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
CIDandportnu
mberarefilledinfromtheclient.VMADDR_CID_ANYisreplacedwiththeCIDofthevirtual
machineandVMADDR_PORT_ANYprovidesanephemeralportfromthenonreservedrange(>=1024).
Theclient(connector)canobtainitslocalCIDbycallingVMCISock_GetLocalCID().
Thebind()functionisthesameasforaregu
larTCPsocketsapplication.
Listen() Function
Thelisten()callpreparestoacceptincomingclientconnections.TheBACKLOGmacropredefinesthenumber
ofincomingconnectionrequeststhatthesystemacceptsbeforerejectingnewones.Thisfunctionisthesame
aslisten()inaregularTCPsocketsapplication.
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
goto close;
}
Accept() Function
Theaccept()callwaitsindefinitelyforanincomingconnectiontoarrive,creating anewsocket(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
descriptorsasNULLiftheprogramcansafelyig
norethem.
if ((select(nfds, &readfd, &writefds, &exceptfds, &timeout) == -1) {
perror("select");
goto close;
}
VMCI Sockets Programming Guide
16 VMware, Inc.
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().See“Select()Function”onpage 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;
}
VMware, Inc. 17
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.See“PreparingtheServ erfora
Connection”onpage 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,
whichmustde
signateaportnotalreadyinuse.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;
}
VMCI Sockets Programming Guide
18 VMware, Inc.
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().
VMware, Inc. 19
4
ThischapterdescribesthedetailsofcreatingVMCIsocketstoreplaceUDPsockets.
“PreparingtheServerforaConnection”onpage 20
“HavingtheClientRequestaConnection”onpage 21
Datagram VMCI Sockets
TheflowchartinFigure 41showshowtoestablishconnectionlesssocketsontheserverandclient.
Figure 4-1. Connectionless Datagram Sockets
InUDPsockets,theserverwaitsfortheclienttotransmit,andacceptsdatagrams.InVMCIsockets,theserver
andclientcommunicatesimilarlywithdatagrams.
Creating Datagram VMCI Sockets
4
socket()
bind()
Server
wait for client datagram
sendto()
recvfrom()
context ID
socket()
Client
sendto()
close() close()
transmit data
reply to data
loop
recvfrom()
VMCI Sockets Programming Guide
20 VMware, Inc.
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
CIDandportnu
mberarefilledinfromtheclient.VMADDR_CID_ANYisreplacedwiththeCIDofthevirtual
machineandVMADDR_PORT_ANYprovidesanephemeralportfromthenonreservedrange(>=1024).
Theclient(connector)canobtainitslocalCIDbycallingVMCISock_GetLocalCID().
TheVMCIsocketsbind()functionisthesameasforaUDPdata
gramapplication.
/