There is of course, no such thing as a UDP connection in the same way there are TCP connections. However the host must still be looked up and a socket obtained before one can send and receive data so in terms of function call sequence, the two forms of communication are conceptually similar. It is the role of this function to do the host lookup and obtain the datagram socket.
| Return Type | Function name | Arguments |
|---|---|---|
| hzEcode | hzUdpClient::Connect | (hzString&,uint32_t,bool,) |
Declared in file: hzUdpClient.h
Defined in file : hzUdpClient.cpp
Function Logic:
Function body:
hzEcode hzUdpClient::Connect (hzString& Hostname)uint32_t nPort, bool bLocal,
{
// There is of course, no such thing as a UDP connection in the same way there are TCP connections. However the host must still be looked up and a socket
// obtained before one can send and receive data so in terms of function call sequence, the two forms of communication are conceptually similar.
//
// It is the role of this function to do the host lookup and obtain the datagram socket.
//
// Arguments: 1) Hostname The server name or IP address (as hzString)
// 2) nPort The port number
// 3) bLocal Optional local flag (if host is this machine)
//
// Returns: E_ARGUMENT If either the hostname or port is not specified.
// E_DNS_NOHOST If the domain does not exist
// E_DNS_NODATA If the domain exists but not a service
// E_DNS_FAILED If the domain has invalid settings
// E_DNS_RETRY If the DNS is busy
// E_NOSOCKET If the socket could not be created or timeouts set
// E_OK If host established and socket obtained
_hzfunc("hzUdpClient::Connect") ;
timeval tv ; // Socket timer
tv.tv_sec = 20;
tv.tv_usec = 0;
/*
** ** Initialize
** */
m_Hostname = Hostname ;
m_nPort = nPort ;
if (!Hostname)
{
hzerr(E_ARGUMENT, "Hostname not set") ;
return E_ARGUMENT ;
}
m_pHost = gethostbyname(*m_Hostname) ;
if (!m_pHost)
{
if (h_errno == TRY_AGAIN) return E_DNS_RETRY ;
if (h_errno == HOST_NOT_FOUND) return E_DNS_NOHOST ;
if (h_errno == NO_RECOVERY) return E_DNS_FAILED ;
if (h_errno == NO_DATA || h_errno == NO_ADDRESS)
return E_DNS_NODATA ;
hzerr(E_DNS_FAILED, "Could not resolve hostname") ;
return E_DNS_FAILED ;
}
if (m_nPort == 0)
{
hzerr(E_ARGUMENT, "Port not set") ;
return E_ARGUMENT ;
}
m_SvrLen = sizeof(m_SvrAddr) ;
/*
** ** Set up socket
** */
memset(&m_SvrAddr, 0,sizeof(m_SvrAddr)) ;
m_SvrAddr.sin_family = AF_INET ;
memcpy(&m_SvrAddr.sin_addr, m_pHost->h_addr, m_pHost->h_length) ;
m_SvrAddr.sin_port = htons(m_nPort) ;
if ((m_nSock = socket(AF_INET, SOCK_DGRAM, 0))< 0)
{
hzerr(E_NOSOCKET, "Could not create client socket") ;
return E_NOSOCKET ;
}
if (setsockopt(m_nSock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) < 0)
{
hzerr(E_NOSOCKET, "Could not set send timeout on UDP client socket") ;
return E_NOSOCKET ;
}
if (setsockopt(m_nSock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
{
hzerr(E_NOSOCKET, "Could not set recv timeout on UDP client socket") ;
return E_NOSOCKET ;
}
return E_OK ;
}