Information Technology Reference
In-Depth Information
structure can be filled with the
sockaddr_in
structure which has the following form:
struct SOCKADDR_IN
{
short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
}
where
sin_family
must be set to
AF_INET
.
sin_port
IP port.
sin_addr
IP address.
sin_zero
padding to make structure the same size as
sockaddr
.
If an application does not care what address is assigned to it, it may specify an Internet ad-
dress equal to
INADDR_ANY
, a port equal to 0, or both. An Internet address equal to
INADDR_ANY
causes any appropriate network interface be used. A port value of 0 causes the
Windows sockets implementation to assign a unique port to the application with a value be-
tween 1024 and 5000.
If no error occurs then it returns a zero value. Otherwise, it returns
INVALID_SOCKET
, and
the specific error code can be tested with
WSAGetLastError
. If an application needs to bind
to an arbitrary port outside of the range 1024 to 5000 then the following outline code can be
used:
#include <windows.h>
#include <winsock.h>
int main(void)
{
SOCKADDR_IN sin;
SOCKET s;
s = socket(AF_INET,SOCK_STREAM,0);
if (s == INVALID_SOCKET)
{
// Socket failed
}
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(100); // port=100
if (bind(s, (LPSOCKADDR)&sin, sizeof (sin)) == 0)
{
// Bind failed
}
return(0);
}
The Windows sockets
htons
function converts an unsigned short (
u_short
) from host byte
order to network byte order.