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
90
91
92
93
94
95
96
97
98
99
100
|
/*
* sturmbahnfahrer
* (c) 2006,2007,2008 by Bram Stolk
* bram at gmail.com
* LICENSED ACCORDING TO THE GPL
*/
#include <sys/socket.h> // for socket()
#include <sys/time.h> // for select()
#include <sys/types.h> // for select()
#include <stdlib.h> // for rand()
#include <time.h> // for time()
#include <netinet/in.h> // for inetaddr_in
#include <arpa/inet.h>
#include <unistd.h> // for gethostname()
#include <errno.h> // for errno
#include <netdb.h> // for gethostbyname()
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "postscore.h"
static char *hostname = "leaderboard.stolk.org";
static const int portnr=7499;
static char msg[1472];
static int sock=0;
static struct sockaddr_in addr;
static socklen_t addrlen;
void postscore_put(const char *username, float tim)
{
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock<0)
perror("socket");
struct hostent *he = gethostbyname(hostname);
if (!he)
perror("gethostbyname");
assert(he);
struct in_addr ip_addr = *(struct in_addr *)(he->h_addr);
char *ipnr = inet_ntoa(ip_addr);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(portnr);
int retval = inet_aton(ipnr, &addr.sin_addr);
if (!retval)
{
perror("inet_aton() failed");
fprintf(stderr,"ipnr = %s\n", ipnr);
}
assert(retval);
addrlen = sizeof(addr);
char m[128];
sprintf(m, "%-8s %6.2f " VERSION_STRING(GAMEVERSION) , username, tim);
int rv = sendto(sock, m, strlen(m), 0, (struct sockaddr*) &addr, addrlen);
if (rv<0)
perror("sendto");
}
const char *postscore_get(void)
{
fd_set readfds;
struct timeval timeout;
FD_ZERO(&readfds);
FD_SET(sock, &readfds);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
int numready = select(sock+1, &readfds, 0, 0, &timeout);
if (numready < 0)
perror("select");
if (numready != 1)
return 0;
int retval = recvfrom(sock, msg, sizeof(msg), 0, (struct sockaddr*) &addr, &addrlen);
if (retval<0)
perror("recvfrom");
msg[retval]=0;
return msg;
}
#ifdef MAIN
int main()
{
char *tags[]={"mazarax","lsd","ree","johan","splendid","warmoes","ferry","superbike"};
srand(time(0));
float score = 40.0 + 40 * (rand()&0xffff) / float(0xffff);
char *name = tags[rand()&7];
postscore_put(name, score);
postscore_get();
}
#endif
|