Академический Документы
Профессиональный Документы
Культура Документы
You can find the most up-to-date technical documentation on our Web site at: http://www.vmware.com/support/ The VMware Web site also provides the latest product updates. If you have comments about this documentation, submit your feedback to: docfeedback@vmware.com
2008 VMware, Inc. All rights reserved. Protected by one or more U.S. Patent Nos. 6,397,242, 6,496,847, 6,704,925, 6,711,672, 6,725,289, 6,735,601, 6,785,886, 6,789,156, 6,795,966, 6,880,022, 6,944,699, 6,961,806, 6,961,941, 7,069,413, 7,082,598, 7,089,377, 7,111,086, 7,111,145, 7,117,481, 7,149,843, 7,155,558, 7,222,221, 7,260,815, 7,260,820, 7,269,683, 7,275,136, 7,277,998, 7,277,999, 7,278,030, 7,281,102, 7,290,253, 7,356,679, 7,409,487, 7,412,492, 7,412,702, 7,424,710, and 7,428, 636; patents pending. VMware, the VMware boxes logo and design, Virtual SMP and VMotion are registered trademarks or trademarks of VMware, Inc. in the United States and/or other jurisdictions. All other marks and names mentioned herein may be trademarks of their respective companies.
VMware, Inc.
Contents
AboutThisBook
1 AboutVMCISockets 7
IntroducingVMCISockets 7 HowVMCISocketsWork 7 PossibleUseCases 8 Performance 8 PersistenceofSockets 8 SocketProgramming 8 FeaturesinSpecificReleases 8 LocationofIncludeFile 9 WebAccesswithStreamVMCISockets 9 NetworkStoragewithDatagramVMCISockets 10
2 PortingtoVMCISockets 11
PortingExistingSocketApplications 11 IncludeaNewHeaderFile 11 ChangeAF_INETtoVMCISockets 11 ObtaintheCID 11 TheVMCISock_GetLocalCID()Function 11 ConnectionOrientedStreamSocket 12 ConnectionlessDatagramSocket 12 InitializingtheAddressStructure 12 CommunicatingBetweenGuests 12 VMCISocketsandNetworking 12 SettingupaNetworklessGuest 12 CommunicatingBetweenGuestandHost 12
3 CreatingStreamVMCISockets 13
StreamVMCISockets 13 PreparingtheServerforaConnection 14 Socket()Function 14 SetandGetSocketOptions 14 Bind()Function 15 Listen()Function 15 Accept()Function 15 Select()Function 15 Recv()Function 16 Send()Function 16 Close()Function 16 Poll()Information 16 Read()andWrite() 16 Getsockname()Function 16 HavingtheClientRequestaConnection 17 Socket()Function 17 Connect()Function 17 Send()Function 17 Recv()Function 18
VMware, Inc. 3
4 CreatingDatagramVMCISockets 19
DatagramVMCISockets 19 PreparingtheServerforaConnection 20 Socket()Function 20 SocketOptions 20 Bind()Function 20 Getsockname()Function 21 Recvfrom()Function 21 Sendto()Function 21 Close()Function 21 HavingtheClientRequestaConnection 21 Socket()Function 21 Sendto()Function 22 Connect()andSend() 22 Recvfrom()Function 22 Close()Function 22
A LearningMoreAboutSockets 23
AboutBerkeleySocketsandWinsock 23 ResourcesontheWeb 23 Wikipedia 23 Sockaddr 23 MSDN 23 LinuxManualPages 24 HardcopyBooks 24
Glossary Index 27
25
VMware, Inc.
TheVMwareVMCISocketsProgrammingGuidedescribeshowtoprogramvirtualmachinecommunications interface(VMCI)sockets,anAPIthatfacilitatesfastandefficientcommunicationbetweenvirtualmachines.
Revision History
VMwarerevisesthisguidewitheachreleaseoftheproductorwhennecessary.Arevisedversioncancontain minorormajorchanges.Table 1summarizesthesignificantchangesineachversionofthisguide. Table 1. Revision History
Revision 20080327 20080620 20080815 Description Firstdraftofthismanualforpossibleinclusioninearlybetareleases. SeconddraftforVMwareWorkstation6.5Beta2andVMwareServer2.0RC1releases. Thirddraft,withsocketoptions,forVMwareWorkstation6.5RCrelease.
Intended Audience
ThisguideisintendedforprogrammerswhoaredevelopingapplicationswithVMCIsocketstocreateCor C++networkingapplicationsthattargetguestoperatingsystemsonVMwarehosts,orvirtualmachine communications.VMCIsocketsarebasedonTCPsockets.Chaptersinthisguideassumesthatyouarefamiliar witheitherBerkeleysocketsorWinsock,theWindowsimplementation.Ifyouarenotfamiliarwithsockets, Appendix Aprovidespointerstolearningresources.
Documentation Resources
ToaccessthecurrentversionsofVMwareAPIandSDKdocumentation,goto: http://www.vmware.com/support/pubs/sdk_pubs.html ToaccessthecurrentversionsofotherVMwaremanuals,goto: http://www.vmware.com/support/pubs
Documentation Feedback
VMwarewelcomesyoursuggestionsforimprovingourdocumentation.Sendyourfeedbackto: docfeedback@vmware.com
VMware, Inc.
Online Support
YoucansubmitquestionsorpostcommentstotheDeveloperCommunitySDKsandAPIsforum,whichis monitoredbyVMwaretechnicalsupportandproductteams.Toaccesstheforum,goto: http://communities.vmware.com/community/developer
Support Offerings
TofindouthowVMwaresupportofferingscanhelpmeetyourbusinessneeds,goto: http://www.vmware.com/support/services
VMware, Inc.
ThischapterintroducesVMCIsockets,discussesreleasespecificfeatures,andillustratesseveralusecases. Topicsinclude: IntroducingVMCISocketsonpage 7 FeaturesinSpecificReleasesonpage 8 WebAccesswithStreamVMCISocketsonpage 9 NetworkStoragewithDatagramVMCISocketsonpage 10 ThisguideassumesthatyouknowabouteitherBerkeleysocketsorWinsock,theWindowsimplementation. Ifyouarenewtosockets,seeAppendix A,LearningMoreAboutSockets,onpage 23.
VMware, Inc.
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.
VMware, Inc.
Linux Firefox
Linux Firefox
IE 7
Apache TCP/IP
Firefox
VMware, Inc.
Programmersusestreamsocketsfortheirhighreliability,anddatagramsocketsforspeedandlowoverhead.
10
VMware, Inc.
VMware, Inc.
11
12
VMware, Inc.
bind()
listen()
Client
socket()
accept() context ID wait for client connection connect() select() establish connection
send()
recv()
close()
VMware, Inc.
13
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.
14
VMware, Inc.
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; }
Listen() Function
Thelisten()callpreparestoacceptincomingclientconnections.TheBACKLOGmacropredefinesthenumber ofincomingconnectionrequeststhatthesystemacceptsbeforerejectingnewones.Thisfunctionisthesame aslisten()inaregularTCPsocketsapplication.
if (listen(sockfd, BACKLOG) == -1) { perror("listen"); goto close; }
Accept() Function
Theaccept()callwaitsindefinitelyforanincomingconnectiontoarrive,creatinganewsocket(andstream descriptornewfd)whenitdoes.Thestructuretheir_addrgetsfilledwithconnectioninformation.
struct sockaddr_vm their_addr; if ((newfd = accept(sockfd, (struct sockaddr *) &their_addr, sizeof their_addr) == -1) { perror("accept"); goto close; }
Select() Function
Theselect()callenablesaprocesstowaitforeventsonmultiplefiledescriptorssimultaneously.This functionhibernates,wakinguptheprocesswhenaneventoccurs.Youcanspecifyatimeoutinsecondsor microseconds.Aftertimeout,thefunctionreturnszero.Youcanspecifytheread,write,andexceptionfile descriptorsasNULLiftheprogramcansafelyignorethem.
if ((select(nfds, &readfd, &writefds, &exceptfds, &timeout) == -1) { perror("select"); goto close; }
VMware, Inc.
15
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.
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.
Socket() Function
InaVMCIsocketsapplication,obtainthenewaddressfamily(domain)toreplaceAF_INET.
int afVMCI = VMCISock_GetAFValue(); if ((sockfd = socket(afVMCI, SOCK_STREAM, 0)) == -1) { perror("socket"); goto exit; }
VMCISock_GetAFValue()returnsadescriptorfortheVMCIsocketsaddressfamilyifavailable.
Connect() Function
Theconnect()callrequestsasocketconnectiontotheserverspecifiedbyCIDinthesockaddr_vmstructure, insteadofbytheIPaddressinthesockaddr_instructure.
struct sockaddr_vm their_addr = {0}; their_addr.svm_family = afVMCI; their_addr.svm_cid = VMCISock_GetLocalCID(); their_addr.svm_port = SERVER_PORT; if ((connect(sockfd, (struct sockaddr *) &their_addr, sizeof their_addr)) == -1) { perror("connect"); goto close; }
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
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.
18
VMware, Inc.
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
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; }
20
VMware, Inc.
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
Socket() Function
ToalteraUDPsocketprogramforVMCIsockets,obtainthenewaddressfamilytoreplaceAF_INET.
int afVMCI = VMCISock_GetAFValue(); if ((sockfd = socket(afVMCI, SOCK_DGRAM, 0)) == -1) { perror("socket"); goto exit; }
VMware, Inc.
21
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; }
Recvfrom() Function
Therecvfrom()calloptionallyreadsdatafromtheserverapplication.SeeRecvfrom()Functiononpage 21.
Close() Function
Theclose()callshutsdownaconnection,giventheoriginalsocketdescriptorobtainedfromthesocket() function.TocompileonWindows,calltheWinsockclosesocket(),asshowninClose()Functionon page 21.
22
VMware, Inc.
ThisappendixintroducesInternetsocketsandprovidespointerstofurtherinformation.
Wikipedia
Hereisanoverviewofthehistoryanddesignofsockets: http://en.wikipedia.org/wiki/Berkeley_sockets
Sockaddr
HereisanoverviewofWinsockdesignandusage: http://www.sockaddr.com/TheSocketsParadigm.html
MSDN
HereisreferenceinformationaboutWinsock: http://msdn2.microsoft.com/enus/library/ms740673(VS.85).aspx
VMware, Inc.
23
Hardcopy Books
InternetworkingwithTCP/IP,Volume3:ClientServerProgrammingandApplications,Linux/PosixSocketsVersion, byDouglasE.ComerandDavidL.Stevens,601pages,PrenticeHall,2000. UNIXNetworkProgramming,Volume1:TheSocketsNetworkingAPI,ThirdEdition,byW.RichardStevens(RIP), BillFenner,andAndrewM.Rudoff,1024pages,AddisonWesley,2003.
24
VMware, Inc.
Glossary
TCP TransmissionControlProtocol,theInternetstandardforconnectionorientedstreamsockets.
VMware, Inc.
25
26
VMware, Inc.
Index
A
about VMCI sockets 7 accept() 15 address structure for sockets 12 AF_INET and PF_INET 23 AF_INET and VMCI sockets 11 afVMCI from VMCISock_GetAFValue() 12, 14, 15, 17
S
select() 15 send() 16, 17 sendto() 21, 22 setsockopt() 14 SO_VMCI_BUFFER_SIZE 14 SOCK_DGRAM 12 SOCK_STREAM 12 socket() 8, 12, 14, 17, 20, 21 stream VMCI sockets 13
B
bind() 12, 15, 20 books about sockets 24
C
close() 16, 18, 21 connect() 17 connectionless socket 12 connection-oriented socket 12 context ID (CID) summary 11
T
technical support resources 6
U
use cases for VMCI sockets 8
D
datagram VMCI sockets 19
V
VMCI library deprecated 7 VMCISock_GetAFValue() 8, 14, 17, 20 VMCISock_GetLocalCID() 11, 15, 17, 20
G
getsockname() 16, 21 getsockopt() 14 guest to guest 8, 12 guest to host 8, 12
W
Web resources about sockets 23 write() 16, 18 WSAStartup() 14, 17, 20
H
hidden information about sockets 23 host to guest 8, 12
I
illustration of datagram VMCI sockets 10 illustration of stream VMCI sockets 9
L
listen() 15
P
PF_INET and AF_INET 23 poll() 16, 18 porting sockets applications 11
R
read() 16, 18 recv() 16, 18
VMware, Inc.
27
28
VMware, Inc.