Data Types and Initialization
The most tedious task when working with Winsock is usually the
initialization and host resolution. Once everything is initialized,
the remaining functions are very easy to work with. Below is a snippet
of source code showing the necessary data types to
create,connect,send and receive data over a network connection.
In order to begin using the Winsock API functions, you must call
the WSAStartup function to initialize Winsock for your application.
Note: MAKEWORD is a macro that simply pushes the two arguments into a
single WORD or 16-bit value.
The next step is to convert the host name to an IP address. In this
example, it is assumed that a valid host name was supplied as a
program argument. The return value will be NULL or a pointer to
a HOSTENT structure that will contain the IP address you wish to
connect to.
We must now allocate enough memory to hold the string representation
of the resolved IP address. This value will be at most "255.255.255.255"
or 16 bytes including the NULL terminator. The memory is then cleared
with the memset function.
The inet_ntoa function is now called to store the IP address as a string.
The h_addr_list element contained in the HOSTENT structure is defined
as "char **" which is why it must be cast as a in_addr structure.
Now that the IP address has been resolved the sockaddr_in structures must
be set up. There is one structure for both the local and remote host.
The last step before using the connect function is to bind the socket.
Binding the socket assigns a local port number and IP address to the
socket you just created. Once your socket is bound, no other application
will be able to claim the local port assigned to your socket.
Previous Page
Next Page