Sunday, March 17, 2013

How to Use Winsock.dll in Visual Basic


1. Open the Visual Basic project you'd like to add winsock.dll support to.
2. Create an empty Visual Basic source code file and add an empty static class to it. It should look something like this:Public Static Class WinsockEnd Class
3. Add each winsock.dll function you'd like to use to your class. For example, to use the function "bind," add the following code:Declare Function bind Lib "winsock.dll" ( _
socketHandle As IntPtr, _
ByRef socketAddress As sockaddr_in, _
addressLength as Integer) As IntegerFor some functions, including "bind," you will need to declare datastructures based on the API. In the case of "bind," you will need to make sure you have declared "sockaddr_in." It can be declared as follows:<StructLayout(LayoutKind.Sequential)> _
Public Structure sockaddr_in
Public sin_family As Short
Public sin_port As Short
Public sin_addr As Integer
Public sin_zero As Integer
End Structure
4. Use your new Winsock functions wherever you need to. To use the "bind" function, for example, write:Dim socketHandle as IntPtr
Dim socketAddress As Winsock.sockaddr_in
Dim addressLength as Integer
Winsock.bind(socketHandle, socketAddress, addressLength)