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
| #include <stdio.h>
#include <string.h>
#include <winsock.h>
#include <io.h>
#define TBUF_LEN 1024
void main(int argc, char **argv)
{
int portno = 4711;
struct sockaddr_in send_addr;
struct sockaddr_in local;
unsigned long inaddr = 0;
SOCKET sockfd;
WSADATA wsaData;
char tbuf[TBUF_LEN];
int ttl = 1;
int flag = 1;
int tcount = 0 ;
WSAStartup(0x0202, &wsaData);
if (LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2 ) {
/* Couldn't find an acceptable WinSock DLL */
WSACleanup();
fprintf(stderr, "%s: failed to find Winsock version 2.2 or better\n",
argv[0]);
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
fprintf(stderr, "%s: can't open stream socket\n", argv[0]);
exit(1);
}
memset((char *) &local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_ANY); // Any address
local.sin_port = htons(0); // Any port
if (bind(sockfd, (struct sockaddr *) &local, sizeof(local)) < 0) {
fprintf(stderr, "%s: failed to bind locally\n", argv[0]);
exit(1);
}
/* TTL Scope Control Value */
if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, (const char *) &ttl, sizeof(ttl)) < 0) {
fprintf(stderr, "%s: failed to set TTL to %d\n", argv[0], ttl);
exit(1);
}
if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, (const char *) &flag, 1) < 0) {
fprintf(stderr, "%s: failed to turn multicast loop according to %d\n", argv[0], flag);
exit(1);
}
/*
* Setup send address
*/
memset((char *) &send_addr, 0, sizeof(send_addr));
send_addr.sin_family = AF_INET;
send_addr.sin_port = htons((u_short) portno);
inaddr = inet_addr("224.16.32.48");
memcpy((char *) &send_addr.sin_addr, (char *) &inaddr, sizeof(inaddr));
for (;;) {
/*
* Setup a message
*/
sprintf(tbuf, "Hello %d", tcount);
/*
* Send a message (including the terminating '\0')
*/
if (sendto(sockfd, tbuf, strlen(tbuf)+1, 0, (const struct sockaddr *) &send_addr, sizeof(send_addr)) < 0) {
fprintf(stderr, "%s: failed to send the message\n error %d", argv[0], WSAGetLastError());
break;
}
Sleep(1000);
tcount++;
} /* End of infinitie sending loop */
WSACleanup();
} |
Partager