Game Development Reference
In-Depth Information
The port and IP address make a unique connection identifier. A server that listens on a
particular port, like 21 for FTP, can accept many hundreds, if not thousands, of con-
nections. A client can even make multiple connections to the same server on the same
port. The IP protocol distinguishes actual connections internally, so they don
'
t get con-
fused, although I
'
d hate to be a programmer trying to debug an application like that!
connect()
Enough already. Here
s the API for actually connecting a socket to a server that is
listening for connections:
'
int connect( 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 connect a socket:
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(ip);
sa.sin_port = htons(port);
if (connect(m_sock, (struct sockaddr *)&sa, sizeof(sa)))
{
// HANDLE ERROR HERE
}
The address family is set to AF_INET since we ' re using the Internet. The IP address
and port are set, and the structure is sent into the connect() function along with
the socket handle. If this didn
t work for some reason, there are two things to try to
help figure out what the problem is.
'
n First, try connecting with Telnet, one of the utility programs you can access
from the command line. If it doesn
'
t work, there
'
s something wrong with the
t see the remote computer.
n If Telnet works, try reversing the byte order of the port or IP address. This is
easy to screw up.
address or port, or perhaps your network can
'
 
Search WWH ::




Custom Search