8/6/2019 Ws65 s2 Vmci Sockets
1/28
VMCI Sockets Programming GuideVMware Workstation 6.5 and VMware Server 2.0
8/6/2019 Ws65 s2 Vmci Sockets
2/28
VMware, Inc.
3401 Hillview Ave.Palo Alto, CA 94304www.vmware.com
2 VMware, Inc.
VMCI Sockets Programming Guide
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:
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 theirrespective companies.
VMCI Sockets Programming Guide
Item: EN-000054-00
http://www.vmware.com/supportmailto:[email protected]://www.vmware.com/supporthttp://www.vmware.com/support/mailto:[email protected]8/6/2019 Ws65 s2 Vmci Sockets
3/28
VMware, Inc. 3
Contents
About
This
Book 5
1 AboutVMCISockets 7IntroducingVMCISockets 7
HowVMCISocketsWork 7
PossibleUseCases 8
Performance 8
PersistenceofSockets 8
SocketProgramming 8
FeaturesinSpecificReleases 8
LocationofIncludeFile 9
WebAccesswithStreamVMCISockets 9
NetworkStoragewithDatagramVMCISockets 10
2 PortingtoVMCISockets 11PortingExistingSocketApplications 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 13StreamVMCISockets 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
8/6/2019 Ws65 s2 Vmci Sockets
4/28
VMCI Sockets Programming Guide
4 VMware, Inc.
Close()Function 18
Poll()Information 18
Read()andWrite() 18
4 CreatingDatagramVMCISockets 19DatagramVMCISockets 19
PreparingtheServerforaConnection 20
Socket()Function 20SocketOptions 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 23AboutBerkeleySocketsandWinsock 23
ResourcesontheWeb 23
Wikipedia 23
Sockaddr 23
MSDN 23
LinuxManualPages 24
HardcopyBooks 24
Glossary 25
Index 27
8/6/2019 Ws65 s2 Vmci Sockets
5/28
VMware, Inc. 5
TheVMwareVMCISocketsProgrammingGuidedescribeshowtoprogramvirtualmachinecommunications
interface(VMCI)sockets,anAPIthatfacilitatesfastandefficientcommunicationbetweenvirtualmachines.
Revision History
VMware
revises
this
guide
with
each
release
of
the
product
or
when
necessary.
A
revised
version
can
contain
minorormajorchanges.Table 1summarizesthesignificantchangesineachversionofthisguide.
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:
About This Book
Table 1. Revision History
Revision Description
20080327 Firstdraftofthismanualforpossibleinclusioninearlybetareleases.
20080620 SeconddraftforVMwareWorkstation6.5Beta2andVMwareServer2.0RC1releases.
20080815 Thirddraft,withsocketoptions,forVMwareWorkstation6.5RCrelease.
http://www.vmware.com/support/pubs/sdk_pubs.htmlhttp://www.vmware.com/support/pubsmailto:[email protected]:[email protected]://www.vmware.com/support/pubshttp://www.vmware.com/support/pubs/sdk_pubs.html8/6/2019 Ws65 s2 Vmci Sockets
6/28
VMCI Sockets Programming Guide
6 VMware, Inc.
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/
http://communities.vmware.com/community/developerhttp://www.vmware.com/support/serviceshttp://www.vmware.com/services/http://www.vmware.com/services/http://www.vmware.com/support/serviceshttp://communities.vmware.com/community/developer8/6/2019 Ws65 s2 Vmci Sockets
7/28
VMware, Inc. 7
1
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.
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.
About VMCI Sockets 1
NOTE TheoriginalVMCIlibrarywasreleasedasanexperimentalClanguageinterfacewithWorkstation6.0.ItincludedadatagramAPIandasharedmemoryAPI.Boththeseinterfaceshavebeendeprecated.
8/6/2019 Ws65 s2 Vmci Sockets
8/28
VMCI Sockets Programming Guide
8 VMware, Inc.
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.
8/6/2019 Ws65 s2 Vmci Sockets
9/28
VMware, Inc. 9
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
WhentheFirefoxbrowsersonLinuxandWindowsrequestaconnectiontotheApacheWebserver,theVMCI
socketslayercreatesasocketendpointandestablishesaconnectionthroughtheVMCIdriverandvirtual
device.TheVMCIsocketslayeronthesystemwithApachereceivestheconnectionandprovidesanaccepted
socketthroughthesocketonwhichApachewaslistening.
Meanwhile,unmodifiedWebbrowsersonthephysicalmachines(WindowshostandLinuxhost)aresending
requeststoeachothersWebserversoverastandardTCP/IPnetworkconnection.Ifguestoperatingsystems
neededtoaccesstheWeboutsidethephysicalmachine,theywouldhavetousedifferent(unmodified)Web
browsers,orhaveafallbackcapabilityoutsideofVMCIsockets.
Firefox
Linux
VMCI socket
VMCI driver
Apache
IE 7Web server
Windows
Windows host
vsocklib.dll
VMCI socket
VMCI driver
VMCI virtual device
TCP/IP
Firefox
Windows
vsocklib.dll
VMCI socket
VMCI driver
Firefox
Linux
VMCI socket
VMCI driver
Apache
FirefoxApache
Linux
Linux host
VMCI socket
VMCI driver
VMCI virtual device
TCP/IP
Firefox
Windows
vsocklib.dll
VMCI socket
VMCI driver
8/6/2019 Ws65 s2 Vmci Sockets
10/28
VMCI Sockets Programming Guide
10 VMware, Inc.
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
Programmersusestreamsocketsfortheirhighreliability,anddatagramsocketsforspeedandlowoverhead.
/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
8/6/2019 Ws65 s2 Vmci Sockets
11/28
VMware, Inc. 11
2
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.
Porting to VMCI Sockets 2
8/6/2019 Ws65 s2 Vmci Sockets
12/28
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
To
initialize
the
address
structure
passed
to
bind(),
insert
these
source
code
statements,
where
sockaddr_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.
8/6/2019 Ws65 s2 Vmci Sockets
13/28
VMware, Inc. 13
3
ThischapterdescribesthedetailsofcreatingVMCIsocketstoreplaceTCPstreamsockets,intwosections:
PreparingtheServerforaConnectiononpage 14
HavingtheClientRequestaConnectiononpage 17
Stream VMCI SocketsTheflowchartinFigure 31showshowtoestablishconnectionorientedsocketsontheserverandclient.
Figure 3-1. Connection-Oriented Stream Sockets
WithVMCIsocketsandTCPsockets,theserverwaitsfortheclienttoestablishaconnection.Afterconnecting,
theserverandclientcommunicatethroughtheattachedsocket.InVMCIsockets,avirtualsocketcanhave
onlytwoendpoints,andtheservercannotinitiateaconnectiontotheclient.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
8/6/2019 Ws65 s2 Vmci Sockets
14/28
VMCI Sockets Programming Guide
14 VMware, Inc.
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().
8/6/2019 Ws65 s2 Vmci Sockets
15/28
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.
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
descriptors
as
NULL
if
the
program
can
safely
ignore
them.if ((select(nfds, &readfd, &writefds, &exceptfds, &timeout) == -1) {
perror("select");
goto close;
}
8/6/2019 Ws65 s2 Vmci Sockets
16/28
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() InformationNotallsocketbasednetworkingprogramsusepoll(),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;
}
8/6/2019 Ws65 s2 Vmci Sockets
17/28
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.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() FunctionTheconnect()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
making
a
connection,
the
VMCISock_GetLocalCID()
function
returns
the
CID
of
the
virtual
machine.Theportnumberisarbitrary,althoughserver(listener)andclient(connector)mustusethesamenumber,
whichmustdesignateaportnotalreadyinuse.Onlyprivilegedprocessescanuseports
8/6/2019 Ws65 s2 Vmci Sockets
18/28
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().
8/6/2019 Ws65 s2 Vmci Sockets
19/28
VMware, Inc. 19
4
ThischapterdescribesthedetailsofcreatingVMCIsocketstoreplaceUDPsockets,intwosections:
PreparingtheServerforaConnectiononpage 20
HavingtheClientRequestaConnectiononpage 21
Datagram VMCI SocketsTheflowchartinFigure 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()
8/6/2019 Ws65 s2 Vmci Sockets
20/28
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
theserver(listener),thiscouldbeanyconnectingvirtualmachine.VMADDR_CID_ANYandVMADDR_PORT_ANY
arepredefinedsothatatbindorconnectiontime,theappropriateCIDandportnumberarefilledinfromtheclient.VMADDR_CID_ANYisreplacedwiththeCIDofthevirtualmachineandVMADDR_PORT_ANYprovidesan
ephemeralportfromthenonreservedrange(>=1024).
Theclient(connector)canobtainitslocalCIDbycallingVMCISock_GetLocalCID().
TheVMCIsocketsbind()functionisthesameasforaUDPdatagramapplication.
8/6/2019 Ws65 s2 Vmci Sockets
21/28
VMware, Inc. 21
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 ConnectionAtthetopofyourapplication,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;
}
8/6/2019 Ws65 s2 Vmci Sockets
22/28
VMCI Sockets Programming Guide
22 VMware, Inc.
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
8/6/2019 Ws65 s2 Vmci Sockets
23/28
VMware, Inc. 23
A
ThisappendixintroducesInternetsocketsandprovidespointerstofurtherinformation.
About Berkeley Sockets and Winsock
Asocketisacommunicationsendpointwithanameandaddressinanetwork.Socketsweremadefamousby
their
implementation
in
Berkeley
UNIX,
and
made
universal
by
their
incorporation
into
Windows.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
Learning More About Sockets A
8/6/2019 Ws65 s2 Vmci Sockets
24/28
VMCI Sockets Programming Guide
24 VMware, Inc.
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 BooksInternetworkingwithTCP/IP,Volume3:ClientServerProgrammingandApplications,Linux/PosixSocketsVersion,
byDouglasE.ComerandDavidL.Stevens,601pages,PrenticeHall,2000.
UNIXNetworkProgramming,Volume1:TheSocketsNetworkingAPI,ThirdEdition,byW.RichardStevens(RIP),
BillFenner,andAndrewM.Rudoff,1024pages,AddisonWesley,2003.
8/6/2019 Ws65 s2 Vmci Sockets
25/28
VMware, Inc. 25
D datagram
Aselfcontainedunitofdatacontainingenoughinformationtoberoutedfromitssourcetoitsdestination
withoutrelianceonearlierexchangesbetweensourceanddestinationhostsandthetransportingnetwork.
I IP
InternetProtocol,thenetworklayeruponwhichTCPandUDParebased.DefinedbytheIETFinRFC791.IPisabesteffortpacketroutingprotocol.In2008,IPv4(version4)isnearlyuniversalbutIPv6(version6)
deploymentsarebeginning.
S socket
Acommunicationsconnectionendpointwithanameandaddressinanetwork.Thetwoendpointsofa
socketcanresideonthesamesystemorondifferentsystemsacrossthenetwork.Socketsaremostoften
usedfornetworkapplications,buttheyarealsousefulforinterprocesscommunicationsonasingleserver.
streamsocketAnetworkconnectionthatprovidesatwoway,sequenced,reliable,unduplicatedflowofdatawithout
recordboundaries,withwelldefinedmechanismsforestablishingconnectionsanddetectingerrors.
T TCP
TransmissionControlProtocol,theInternetstandardforconnectionorientedstreamsockets.
U UDP
UserDatagramProtocol,theInternetstandardforconnectionlessdatagramsockets.
V VMCI
Virtualmachinecommunicationinterface,asharedmemoryAPIanddatagraminterfacenowreplacedby
VMCIsockets,astreamanddatagramsocketsinterface.
Glossary
8/6/2019 Ws65 s2 Vmci Sockets
26/28
VMCI Sockets Programming Guide
26 VMware, Inc.
8/6/2019 Ws65 s2 Vmci Sockets
27/28
VMware, Inc. 27
Index
Aabout VMCI sockets 7accept() 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
B
bind() 12, 15, 20
books about sockets 24
Cclose() 16, 18, 21
connect() 17
connectionless socket 12
connection-oriented socket 12
context ID (CID) summary 11
D
datagram VMCI sockets 19
G
getsockname() 16, 21
getsockopt() 14
guest to guest 8, 12
guest to host 8, 12
H
hidden information about sockets 23
host to guest 8, 12
I
illustration of datagram VMCI sockets 10
illustration of stream VMCI sockets 9
Llisten() 15
P
PF_INET and AF_INET 23
poll() 16, 18
porting sockets applications 11
R
read() 16, 18
recv() 16, 18
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
T
technical support resources 6
U
use cases for VMCI sockets 8
V
VMCI library deprecated 7
VMCISock_GetAFValue() 8, 14, 17, 20
VMCISock_GetLocalCID() 11, 15, 17, 20
W
Web resources about sockets 23
write() 16, 18
WSAStartup() 14, 17, 20
8/6/2019 Ws65 s2 Vmci Sockets
28/28
VMCI Sockets Programming Guide
Top Related