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
|
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h> /* close() */
#define TEMP_CLIENT_DUMP_FILE "client.dat"
#define SERVER_PORT 11111
#define SERVER_IP_ADDRESS "192.168.1.108"
#define BUFFSIZE 8
void error(char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char *argv[]) {
struct sockaddr_in serv_addr;
char buffer[BUFFSIZE];
int socketId, readBytes;
int n;
unsigned long totalReadBytes;
FILE *fp;
/* Create the socket */
socketId = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (socketId < 0) {
error("ERROR opening socket");
}
/* Construct the server sockaddr_in structure */
memset(&serv_addr, 0x00, sizeof (serv_addr)); /* Clear struct */
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP_ADDRESS); /* IP address */
serv_addr.sin_port = htons(SERVER_PORT); /* server port */
if ((fp = fopen(TEMP_CLIENT_DUMP_FILE, "wb")) == NULL) {
fprintf(stderr, "ERROR, unable to create file\n");
exit(0);
}
/* Establish connection */
fprintf(stdout, "connectd server %s:%d...\n", inet_ntoa(serv_addr.sin_addr), serv_addr.sin_port/*ntohs(servAddr.sin_port)*/);
totalReadBytes = 0;
//while (1) {
readBytes = bind(socketId, (struct sockaddr *) & serv_addr, sizeof (serv_addr));
if (readBytes == 0) {
n = sizeof (serv_addr);
do {
readBytes = recvfrom(socketId, buffer, BUFFSIZE, 0, (struct sockaddr *) & serv_addr, &n);
if (readBytes > 0) {
totalReadBytes = totalReadBytes + fwrite(buffer, 1, readBytes, fp);
printf("Total read bytes %d \r", totalReadBytes);
}
} while (readBytes > 0);
}else{
printf("unable to bind\n");
}
//}
close(socketId);
fclose(fp);
return 0;
}
| |