1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
|
#include <windows.h>
#include <winsock.h>
#include <stdio.h>
#include <conio.h>
//automatically link with winsock
#pragma comment(lib, "wsock32.lib")
// Address definitions to be used in the multicast() function
#define MULTICAST_GROUP_IP "234.5.6.7"
#define DEFAULT_PORT 15
#define DEFAULT_TTL 7
#define STRING_LENGTH 100
// Bread&butter error reporting
void PrintWinsockError()
{
LPVOID lpMsgBuf;
int iError = WSAGetLastError();
if(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, iError, 0, (LPTSTR)&lpMsgBuf, 0, 0))
{
cprintf("WSAGetLastError %d: %s", iError, lpMsgBuf);
LocalFree(lpMsgBuf);
}
else
{
cprintf("WSAGetLastError %d", iError);
}
}
// Address-to-ip resolution
int iResolve(SOCKADDR_IN &addrResolve, char *cHost, UINT uiPort, UINT uiInterface)
{
struct in_addr iaHost; // Used to resolve IP and connect
LPHOSTENT lpHost; // Used to connect
unsigned int iIndex;
iaHost.s_addr = inet_addr((LPCSTR)cHost); // Check if this syntax is consistent with IP address
if(iaHost.s_addr == INADDR_NONE) // If not IP, must be hostname string
{
lpHost = gethostbyname(cHost); // Get host structure by host name
if(lpHost == NULL)return false; // Whoops! Unresolved hostname!
}
else // This is an IP so just get structure by address
{
lpHost = gethostbyaddr((LPCSTR)&iaHost, sizeof(struct in_addr), AF_INET); // Get host structure by address
if(lpHost == NULL)return false; // Whoops! Unresolved host IP!
}
for(iIndex = 0; iIndex < uiInterface; iIndex++)
if(!lpHost->h_addr_list[iIndex])
return false;
if(!lpHost->h_addr_list[uiInterface])
return false;
memset(&addrResolve, NULL, sizeof(addrResolve));
addrResolve.sin_family = AF_INET; // We only use internet addresses
addrResolve.sin_addr = *((LPIN_ADDR)lpHost->h_addr_list[uiInterface]); // The remote IP
addrResolve.sin_port = htons(uiPort); // The remote port
// Okays
return true;
}
// Work out which ip comes first on this machine, or nth ip if iInterface is specified
bool bGetNetworkInterface(IN_ADDR &in_addrLocal, unsigned int uiInterface = 0)
{
char cLocalHostName[MAX_PATH];
gethostname(cLocalHostName, sizeof(cLocalHostName));
SOCKADDR_IN addrLocal;
if(!iResolve(addrLocal, cLocalHostName, 0, uiInterface))
return false;
in_addrLocal = addrLocal.sin_addr;
return true;
}
// Function to associate a socket with a multicast group
bool bJoinMulticastGroup(SOCKET UDP_Socket, char *cMulticastGroup)
{
// Used to set multicast TTL
char cTTL = DEFAULT_TTL;
// Set the multicast ttl
int iRet = setsockopt(UDP_Socket, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&cTTL, sizeof(cTTL));
if(iRet == SOCKET_ERROR)
{
cprintf("Failed to set multicast ttl\r\n");
PrintWinsockError();
return false;
}
// Add socket to be a member of the multicast group
struct ip_mreq ipmr;
ipmr.imr_multiaddr.s_addr = inet_addr(cMulticastGroup);
bGetNetworkInterface(ipmr.imr_interface); // Does the job of... ipmr.imr_interface.s_addr = inet_addr("ip");
iRet = setsockopt(UDP_Socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ipmr, sizeof(ipmr));
if(iRet == SOCKET_ERROR)
{
cprintf("Failed to add multicast membership\r\n");
PrintWinsockError();
return false;
}
// Set the local interface from which multicast is to be transmitted
IN_ADDR inLocal;
bGetNetworkInterface(inLocal); // Does the job of inLocal = inet_addr("ip");
setsockopt(UDP_Socket, IPPROTO_IP, IP_MULTICAST_IF, (char *)&inLocal, sizeof(inLocal));
if(iRet == SOCKET_ERROR)
{
cprintf("Failed to set multicast interface\r\n");
PrintWinsockError();
return false;
}
return true;
}
// Function that receives UDP packets (not just multicast ones)
bool bReceiveMulticast(SOCKET UDP_Socket, char *cMulticastGroup)
{
// Used to identify where the packet came from
SOCKADDR_IN addrFrom;
// String to hold the packet data
char cData[STRING_LENGTH];
// Holds status of incoming packet queue
ULONG ulQueue[1];
// Tracks if any packets are received
bool bGotPacket = false;
while(true)
{
// Did a packet come through?
*ulQueue = NULL; // Reset incoming packet status
if(ioctlsocket(UDP_Socket, FIONREAD, (ULONG FAR *)ulQueue)) // Ask the socket how many packets are waiting
{
cprintf("ioctlsocket failed\r\n");
PrintWinsockError();
return false;
}
// No packets waiting?
if(!*ulQueue)
break;
// Receive the packet
int size = sizeof(addrFrom);
int iRet = recvfrom(UDP_Socket, (char *)cData, sizeof(cData) - 1, 0, (struct sockaddr*)&addrFrom, &size);
if(iRet == SOCKET_ERROR)
{
cprintf("Packet arrived, but failed to be received\r\n");
PrintWinsockError();
return false;
}
// Terminate packet so we can display it as a string
cData[iRet] = 0;
// Print the contents of the packet
cprintf("Received packet from %s: \"%s\"\r\n", inet_ntoa(addrFrom.sin_addr), cData);
bGotPacket = true;
}
// If no packets received, inform the user
if(!bGotPacket)
cprintf("No packets received\r\n");
return true;
}
// Function that sends a multicast
bool bSendMulticast(SOCKET UDP_Socket, char *cMulticastGroup)
{
// Used to track return values of functions
int iRet;
// Where the packet will be heading
SOCKADDR_IN addrDest;
memset(&addrDest, 0, sizeof(addrDest));
// String to hold the packet data
char cData[STRING_LENGTH];
// Destination IP Address
addrDest.sin_family = AF_INET;
addrDest.sin_port = htons(DEFAULT_PORT);
addrDest.sin_addr.s_addr = inet_addr(cMulticastGroup);
// Data to send
memset(cData, 0, sizeof(cData));
wsprintf((char *)cData, "Hello World!");
// Send to MULTICAST
iRet = sendto(UDP_Socket, (char *)cData, (int)strlen(cData), 0, (struct sockaddr*)&addrDest, sizeof(addrDest));
if(iRet == SOCKET_ERROR)
{
cprintf("Packet failed to be sent\r\n");
PrintWinsockError();
return false;
}
return true;
}
// Application entry point
int main(int argc, char *argv[], char *envp[])
{
// Local for return value checking
int iRet;
// Used for winsock startup
WORD wVersionRequested;
WSADATA wsaData;
// Initialise winsock, latest version
wVersionRequested = MAKEWORD(2, 2);
iRet = WSAStartup(wVersionRequested, &wsaData);
if(iRet != 0)
{
WSACleanup();
cprintf("Failed to start winsock\r\n");
return false;
}
// Create a new socket
SOCKET UDP_Socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(UDP_Socket==INVALID_SOCKET)
{
cprintf("Failed to create socket\r\n");
PrintWinsockError();
return false;
}
// Bind socket to port
SOCKADDR_IN addrLocal;
addrLocal.sin_family = AF_INET;
addrLocal.sin_port = htons(DEFAULT_PORT);
bGetNetworkInterface(addrLocal.sin_addr); // Same as... addrLocal.sin_addr.s_addr = inet_addr("yourip");
iRet = bind(UDP_Socket, (LPSOCKADDR)&addrLocal, sizeof(struct sockaddr));
if(iRet == SOCKET_ERROR)
{
cprintf("Failed to bind socket\r\n");
PrintWinsockError();
return false;
}
cprintf("Using UDP port %d, press any key to exit\r\n", DEFAULT_PORT);
cprintf("Attempting to join multicast group %s... ", MULTICAST_GROUP_IP);
// Join multicasting group
if(bJoinMulticastGroup(UDP_Socket, MULTICAST_GROUP_IP))
cprintf("done\r\n\r\n");
else
cprintf("FAILED\r\n");
while(true)
{
// Send a multicast packet
if(bSendMulticast(UDP_Socket, MULTICAST_GROUP_IP))
cprintf("Multicast sent to group %s\r\n", MULTICAST_GROUP_IP);
// Wait for echo packet to arrive, just in case the network is laggy
Sleep(100);
// Receive a packet
bReceiveMulticast(UDP_Socket, MULTICAST_GROUP_IP);
// Dont overwhelm the user
Sleep(1000);
if(kbhit())break;
Sleep(1000);
if(kbhit())break;
Sleep(1000);
if(kbhit())break;
}
// Close socket, kill winsock
closesocket(UDP_Socket);
WSACleanup();
// Quit
return iRet;
}
|