OWLNext    7.0
Borland's Object Windows Library for the modern age
Loading...
Searching...
No Matches
Sending Data From a Datagram Socket

The code below sends a C string by datagram to a given peer on a given port.

Both blocking and non-blocking code is demonstrated. Note that the switch back and forth between blocking and non-blocking mode involves only a single line of code. Note also that after the last write call, the local TDatagramSocket object is deleted without any closesocket() function being called. This is because the socket cleans up after itself and calls CloseSocket() if it had not been called already.

#define N_PORT 501
#define SZ_PEER_ADDR "132.162.211.199"
char szString[] ="Hello";
TDatagramSocket myDatagramSocket(TINetSocketAddress(htons(N_PORT)));
myDatagramSocket.CreateSocket();
myDatagramSocket.BindSocket();
myDatagramSocket.SetPeerAddress(TINetSocketAddress(ntohs(N_PORT), inet_addr(SZ_PEER_ADDR));
myDatagramSocket.Write(szString, sizeof(szString)); //blocking write call.
myDatagramSocket.StartRegularNotification();
//socket is now non-blocking.
myDatagramSocket.Write(szString, sizeof(szString)) //non-blocking write call.
myDatagramSocket.CancelNotification();
//socket is blocking again.
myDatagramSocket.Write(szString, sizeof(szString)); //blocking write call.
} //The socket will clean up after itself; you don't have to.

The code below broadcasts a C string on the network, minus error-checking. Note that when you broadcast with the address "INADDR_BORADCAST", you don't need to say htonl(INADDR_BROADCAST) or inet_addr(INADDR_BORADCAST). This is because the definition for INADDR_BROADCAST and its related predefined addresses are already in binary network format.

#define N_PORT 501
char szString[]="Hello Everybody";
TINetSocketAddress myINetAddress (0, INADDR_ANY);
TDatagramSocket myDatagramSocket(myINetAddress);
myDatagramSocket.CreateSocket();
myDatagramSocket.BindSocket();
myDatagramSocket.SetBroadcastOption(true); //enable broadcasting
myDatagramSocket.Write(szString, sizeof(szString)); //blocking write call.
}