Declare Function socket Lib "wsock32.dll" (ByVal af As Long, ByVal prototype As Long, ByVal protocol As Long) As Long
socket creates a new socket used for network communications. The socket is assigned a particular communications protocol (such as TCP/IP) upon creation. Before using this function, Winsock must be initialized via calling WSAStartup.
If successful, the function returns a descriptor of the socket that was created. If an error occured, the function returns INVALID_SOCKET (use WSAGetLastError to get the error code).
None.
Const INVALID_SOCKET = &HFFFFFFFF
Download the main page of this web site (http://www.vbapi.com). This example supports a very crude implementation of HyperText Transport Protocol (HTTP), sending a request to the server and receiving the document. The document downloaded, with HTTP headers removed, is output to the Debug window. To prevent the program from appearing to lock up in the event of a momentary interruption in the transfer, a nonblocking socket is used. To use this example, place a command button named cmdDownload on a form window.
Note the careful use of GoTo in this example. Since there are lots of things that can go wrong, and WSACleanup must be called at the end no matter what happens, the GoTo statements skip down to the end if an unrecoverable error occurs. If VB had better exception handling, I would use that instead of GoTo.
' This code is licensed according to the terms and conditions listed here.
' Declarations and such needed for the example:
' (Copy them to the (declarations) section of a module.)
Public Type WSADATA
wVersion As Integer
wHighVersion As Integer
szDescription As String * 257
szSystemStatus As String * 129
iMaxSockets As Long
iMaxUdpDg As Long
lpVendorInfo As Long
End Type
Public Declare Function WSAStartup Lib "wsock32.dll" (ByVal wVersionRequested As Integer, lpWSAData _
As WSADATA) As Long
Public Declare Function WSACleanup Lib "wsock32.dll" () As Long
Public Const AF_INET = 2
Public Const SOCK_STREAM = 1
Public Declare Function gethostbyname Lib "wsock32.dll" (ByVal name As String) As Long
Public Type hostent
h_name As Long
h_aliases As Long
h_addrtype As Integer
h_length As Integer
h_addr_list As Long
End Type
Public Declare Function htons Lib "wsock32.dll" (ByVal hostshort As Integer) As Integer
Public Declare Function socket Lib "wsock32.dll" (ByVal af As Long, ByVal prototype As Long, _
ByVal protocol As Long) As Long
Public Type sockaddr
sin_family As Integer
sin_port As Integer
sin_addr As Long
sin_zero As String * 8
End Type
Public Declare Function connect Lib "wsock32.dll" (ByVal s As Long, name As sockaddr, ByVal namelen _
As Long) As Long
Declare Function ioctlsocket Lib "wsock32.dll" (ByVal s As Long, ByVal cmd As Long, argp As Long) As Long
Public Const FIONBIO = &H8004667E
Public Declare Function send Lib "wsock32.dll" (ByVal s As Long, buf As Any, ByVal length As Long, _
ByVal flags As Long) As Long
Public Declare Function recv Lib "wsock32.dll" (ByVal s As Long, buf As Any, ByVal length As Long, _
ByVal flags As Long) As Long
Public Declare Function closesocket Lib "wsock32.dll" (ByVal s As Long) As Long
Public Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (Destination As Any, Source _
As Any, ByVal Length As Long)
Public Const SOCKET_ERROR = -1
' Define a useful macro.
Public Function MAKEWORD(ByVal bLow As Byte, ByVal bHigh As Byte) As Integer
MAKEWORD = Val("&H" & Right("00" & Hex(bHigh), 2) & Right("00" & Hex(bLow), 2))
End Function
' *** Place the following code inside the form window. ***
Private Sub cmdDownload_Click()
Dim wsockinfo As WSADATA ' info about Winsock
Dim sock As Long ' the socket descriptor
Dim pHostinfo As Long ' pointer to info about the host computer
Dim hostinfo As hostent ' info about the host computer
Dim pIPAddress As Long ' pointer to host's IP address
Dim ipAddress As Long ' host's IP address
Dim sockinfo As sockaddr ' settings for the socket
Dim buffer As String ' buffer for sending and receiving data
Dim reply As String ' accumulates server's reply
Dim retval As Long ' generic return value
' Begin a Winsock session.
retval = WSAStartup(MAKEWORD(2, 2), wsockinfo)
If retval <> 0 Then
Debug.Print "Unable to initialize Winsock! --"; retval
Exit Sub
End If
' Get information about the server to connect to.
pHostinfo = gethostbyname("www.vbapi.com")
If pHostinfo = 0 Then
Debug.Print "Unable to resolve host!"
GoTo Cleanup
End If
' Copy information about the server into the structure.
CopyMemory hostinfo, ByVal pHostinfo, Len(hostinfo)
If hostinfo.h_addrtype <> AF_INET Then
Debug.Print "Couldn't get IP address of www.vbapi.com!"
GoTo Cleanup
End If
' Get the server's IP address out of the structure.
CopyMemory pIPAddress, ByVal hostinfo.h_addr_list, 4
CopyMemory ipAddress, ByVal pIPAddress, 4
' Create a socket.
sock = socket(AF_INET, SOCK_STREAM, 0)
If sock = SOCKET_ERROR Then
Debug.Print "Unable to create socket!"
GoTo Cleanup
End If
' Make a connection to www.vbapi.com:80 (where the web server listens).
With sockinfo
' Use Internet Protocol (IP)
.sin_family = AF_INET
' Connect to port 80.
.sin_port = htons(80)
' Connect to this IP address.
.sin_addr = ipAddress
' Padding characters.
.sin_zero = String(8, vbNullChar)
End With
Debug.Print "Attempting to connect...."
retval = connect(sock, sockinfo, Len(sockinfo))
If retval <> 0 Then
Debug.Print "Unable to connect!"
GoTo Cleanup
End If
' Send an HTTP/GET request for the /index.html file.
buffer = "GET / HTTP/1.1" & vbCrLf & _
"Host: www.vbapi.com" & vbCrLf & _
"User-Agent: HTTP-Test-Program" & vbCrLf & vbCrLf
retval = send(sock, ByVal buffer, Len(buffer), 0)
Debug.Print "Sent request. Waiting for reply..."
' Make the socket non-blocking, so calls to recv don't halt the program waiting for input.
retval = ioctlsocket(sock, FIONBIO, 1)
' Read the response from the other system. A more sophisticated program
' would watch to see if the connection ever times out (i.e., if the connection is
' lost). For brevity, such code is omitted here.
Do
buffer = Space(4096)
retval = recv(sock, ByVal buffer, Len(buffer), 0)
If retval <> 0 And retval <> SOCKET_ERROR Then
reply = reply & Left(buffer, retval)
End If
' Process background events so the program doesn't appear to freeze.
DoEvents
Loop Until retval = 0
' Print the response from the server.
Debug.Print "Document Retrieved:"
Debug.Print reply
' Perform the necessary cleanup at the end.
Cleanup:
retval = closesocket(sock)
retval = WSACleanup()
End Sub
Back to the Function list.
Back to the Reference section.
Last Modified: January 21, 2001
This page is copyright © 2001 Paul Kuliniewicz.
Copyright Information Revised October 29, 2000
Go back to the Windows API Guide home page.
E-mail: vbapi@vbapi.com Send Encrypted E-Mail
This page is at http://www.vbapi.com/ref/s/socket.html