Код:
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), sendto(), and recvfrom() */
#include <arpa/inet.h> /* for sockaddr_in and inet_addr() */
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include <pthread.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
/* Longest chunk of data to receive */
#define max_chunk_length 2097152
#define total_length 100*1048576
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#define min(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
void DieWithError(char *errorMessage)
{
printf("%s",errorMessage);
exit(1);
} /* External error handling function */
int main(int argc, char *argv[])
{
int sock; /* Socket */
struct sockaddr_in broadcastAddr; /* Broadcast Address */
unsigned short broadcastPort; /* Port */
long recvChunkLen; /* Length of received string */
void *megabuf=NULL;
unsigned long dataLength=0;
int fh2;
int res;
int a=max_chunk_length;
megabuf=malloc(total_length); //1 gbyte of data
if (!megabuf) DieWithError("didn't get memory");
if (argc != 2) /* Test for correct number of arguments */
{
fprintf(stderr,"Usage: %s <Broadcast Port>\n", argv[0]);
exit(1);
}
broadcastPort = atoi(argv[1]); /* First arg: broadcast port */
/* Create a best-effort datagram socket using UDP */
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
DieWithError("socket() failed");
/* Construct bind structure */
memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */
broadcastAddr.sin_family = AF_INET; /* Internet address family */
broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
broadcastAddr.sin_port = htons(broadcastPort); /* Broadcast port */
setsockopt(sock, SOL_SOCKET,SO_RCVBUF,&a,sizeof(a));
/* Bind to the broadcast port */
if (bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) < 0)
DieWithError("bind() failed");
/* Receive a single datagram from the server */
while(1)
{
if ((recvChunkLen = recvfrom(sock, &megabuf[dataLength], min(max_chunk_length,total_length-dataLength), 0, NULL, 0)) < 0)
DieWithError("recvfrom() failed");
dataLength+=recvChunkLen;
/* Print count of received bytes */
if (dataLength>=total_length) {printf("Received %lu bytes\n", dataLength); dataLength=0;}
}
close(sock);
fh2 = open("data.raw", O_WRONLY | O_CREAT | O_TRUNC, 0777);
dataLength=0;
while(dataLength<total_length)
{
res=write(fh2, &megabuf[dataLength], 1048576);
if (res == -1)
{
close(fh2);
free(megabuf);
perror("Error during writing wave data");
exit(1);
}
dataLength+=1048576;
}
close(fh2);
free(megabuf);
exit(0);
}