Game Development Reference
In-Depth Information
Server Functions
You
re ready to create a
server-side socket. You create the socket handle with the same socket() function
you saw earlier, and you are free to also call the setsockopt() function to set the
options you want. Instead of calling connect() , though, you call two other func-
tions: bind() and listen() .
'
ve seen how to create sockets on the client side, so now you
'
bind()
A server has to bind a socket to a particular IP address and port within the system
before it can accept connections. After it is bound to an address and a port, you call
listen() to open the server side for client connections:
int bind( SOCKET s, const struct sockaddr* name, int namelen);
Parameters:
n Socket: A valid socket handle.
n Name: A structure that holds the address family, port, and address of the server.
n NameLen: Always sizeof(struct sockaddr) .
Return Value:
Returns zero if the function succeeded or SOCKET_ERROR if there was an error.
Here
s an example of how you bind a socket to a particular port using the local IP
address of the server. The port is specified in the struct sockaddr in network byte
order. The address family is AF_INET for Internet addresses, and since we want the
socket to be bound to the local IP address, the address member is set to ADDR_ANY .
'
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr = ADDR_ANY;
sa.sin_port = htons(portnum);
if (bind(m_sock, (struct sockaddr *)&sa, sizeof(sa)))
{
// HANDLE ERROR HERE
}
listen()
After you
ve bound a socket to a particular port, you can open it up to accept con-
nections with the listen() function:
'
int listen( SOCKET s, int backlog);
 
 
Search WWH ::




Custom Search