Features/Real rng device/VirtRng-RandBytes.cpp

From QEMU
Jump to: navigation, search
$ cat RandBytes.cpp 
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <qwqng.hpp>

#include <sys/socket.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>


QWQNG* QNG;

int main(void)
{
	int qngStatus = 0;

	printf("Start Device...\n\n"); 
	QNG = new QWQNG(); // create class

	/* Print Status String */ 
	char* statusString; 
	statusString = QNG->StatusString();
	printf("Status: %s\n\n", statusString);             	

	/* Print open device serial number */
	char* SerialNumber; 
	SerialNumber = QNG->DeviceID();
	printf("DeviceID: %s\n\n", SerialNumber);

	char* randbyte;	
	int bytecount;	
	bytecount = 10;
	randbyte = new char [bytecount];

	int sock_fd, accept_sock;
	struct sockaddr_in server_addr;

	server_addr.sin_family=AF_INET;
	server_addr.sin_port=htons(1024);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
		exit(1);
	}
	if (bind(sock_fd, (struct sockaddr *)&server_addr,
				sizeof(struct sockaddr)) < 0) {
		exit(1);
	}
	if (listen(sock_fd,4) < 0) {
		exit(1);
	}

	if ((accept_sock = accept(sock_fd, NULL, NULL)) < 0) {
		exit(1);
	}
	/* Get 10 random bytes */
	printf("Get 10 Random Bytes ..\n"); 
	int count = 0;
	while(1) {
		if ((qngStatus = QNG->RandBytes(randbyte, bytecount)) != S_OK) {
			printf("Error: %s\n\n", QNG->StatusString());
			return EXIT_FAILURE;
		}
		count %= 100000;
		if (count++ == 0) {
			printf("working....\n");
		}
		send(accept_sock, randbyte, sizeof(randbyte), 0);
	}

	delete [] randbyte;
	delete QNG;
	printf("EXIT..."); 
	return EXIT_SUCCESS;
}