Skip to content

Instantly share code, notes, and snippets.

@murachue
Created June 7, 2014 13:24
Show Gist options
  • Save murachue/52bdd403c30295c82995 to your computer and use it in GitHub Desktop.
Save murachue/52bdd403c30295c82995 to your computer and use it in GitHub Desktop.
Random bytes server for Windows.
// cl randomd.cpp /nologo /O2 /MD ws2_32.lib bcrypt.lib
// http://www.geekpage.jp/programming/winsock/
// http://code.msdn.microsoft.com/windowsdesktop/Random-Number-Generation-e5b88ccc/sourcecode?fileId=42843&pathId=1800936463
#include <windows.h>
//#include <tchar.h>
//#include <winsock2.h>
#include <bcrypt.h>
#include <stdio.h>
#include <winternl.h>
int main(int argc, char *argv[]) {
if(argc < 2) {
printf("usage: %s <port>\n", argv[0]);
return 1;
}
int port = atoi(argv[1]);
WSADATA wsa;
int err;
if((err = WSAStartup(MAKEWORD(2, 0), &wsa)) != 0) {
printf("WSAStartup error: %08X\n", err);
return 1;
}
SOCKET sock;
if((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { // AF? PF??
printf("socket error: %08X\n", WSAGetLastError());
return 1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
BOOL yes = 1;
if((err = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(yes))) != 0) {
printf("setsockopt/SO_REUSEADDR error: %08X\n", err);
return 1;
}
if((err = bind(sock, (struct sockaddr*)&addr, sizeof(addr))) != 0) {
printf("bind error: %08X\n", err);
return 1;
}
if((err = listen(sock, 5)) != 0) { // 5 backlog
printf("listen error: %08X\n", err);
return 1;
}
for(;;) {
SOCKET s;
struct sockaddr_in claddr;
int len = sizeof(claddr);
if((s = accept(sock, (struct sockaddr*)&claddr, &len)) == INVALID_SOCKET) {
printf("accept error: %08X\n", WSAGetLastError());
return 1;
}
printf("connection from %s:%d\n", inet_ntoa(claddr.sin_addr), ntohs(claddr.sin_port));
for(;;) {
unsigned char buf[4096];
NTSTATUS st;
if(!NT_SUCCESS(st = BCryptGenRandom(NULL, buf, sizeof(buf), BCRYPT_USE_SYSTEM_PREFERRED_RNG))) {
printf("BCryptGenRandom error: %08X\n", st);
break;
}
err = send(s, (const char*)buf, sizeof(buf), 0);
if(err == SOCKET_ERROR) {
err = WSAGetLastError();
if(err == WSAECONNRESET) {
printf("got WSAECONNRESET.\n", err);
} else {
printf("send error: %08X\n", err);
}
break;
}
if(err == 0) {
printf("send returns 0...\n");
break;
}
if(err < sizeof(buf)) {
printf("send returns %d...\n", err);
break;
}
}
closesocket(s);
printf("disconnected.\n");
}
WSACleanup();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment