When UDP sends data:
Csocket m_sendsock; // defines a network socket.
M_sendsock.close ();
Char szhostname [128] = {0 };
Gethostname (szhostname, 128 );
Hostent * phostent = gethostbyname (szhostname );
Char * pszip = inet_ntoa (* (in_addr *) & phostent-> h_addr_list [2]);
Cstring szport; // obtain the local port
M_port.getwindowtext (szport );
Int nport = atoi (szport );
If (! M_sendsock.create (nport, sock_dgram, pszip ))
{
MessageBox ("failed to create socket ");
}
Else
{
Bool bcmdopt = true;
M_sendsock.setsockopt (so_broadcast, (void *) & bcmdopt, 1); // set the socket to broadcast socket
Cstring szsendinfo; // sending information
Cstring szsendport; // The sending port.
M_sendcontent.getwindowtext (szsendinfo); // get the sending information
M_sendport.getwindowtext (szsendport );
Int nsendport = atoi (szsendport );
Sockaddr_in ADDR;
ADDR. sin_family = af_inet;
ADDR. sin_addr.s_un.s_addr = inaddr_broadcast;
ADDR. sin_port = htons (nsendport );
M_sendsock.sendto (szsendinfo. getbuffer (0), szsendinfo. getlength (),
(Sockaddr *) & ADDR, sizeof (ADDR ));
}
When UDP receives data:
// Obtain the IP address
Char szhostname [128];
Gethostname (szhostname, 128 );
Hostent * phostent = gethostbyname (szhostname );
Char * pszip = inet_ntoa (* (in_addr *) & phostent-> h_addr_list [2]);
M_localsock.setdialog (this );
M_localsock.create (8021, sock_dgram, pszip );
Bool bcmdopt = true;
M_localsock.setsockopt (so_broadcast, (void *) & bcmdopt, 1 );
Int nrecvnum = socket. receivefrom (pbuffer, 1024, szip, nport );
If (nrecvnum! =-1)
{
M_recvinfo.setwindowtext (pbuffer );
}