-
Notifications
You must be signed in to change notification settings - Fork 0
/
bt_lib.cpp
83 lines (64 loc) · 1.76 KB
/
bt_lib.cpp
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h> //internet address library
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sstream>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <openssl/sha.h> //hashing pieces
#include "bt_lib.h"
int bt_lib::init_peer(peer_t* peer, char* id, char* ip, unsigned short port) {
struct hostent * hostinfo;
//set the host id and port for referece
memcpy(peer->id, id, ID_SIZE);
peer->port = port;
//get the host by name
if((hostinfo = gethostbyname(ip)) == NULL){
perror("gethostbyname failure, no such host?");
herror("gethostbyname");
exit(1);
}
//zero out the sock address
bzero(&(peer->sockaddr), sizeof(peer->sockaddr));
//set the family to AF_INET, i.e., Iternet Addressing
peer->sockaddr.sin_family = AF_INET;
//copy the address to the right place
bcopy((char *) (hostinfo->h_addr),
(char *) &(peer->sockaddr.sin_addr.s_addr),
hostinfo->h_length);
//encode the port
peer->sockaddr.sin_port = htons(port);
return 0;
}
void bt_lib::calc_id(char* ip, unsigned short port, char* id) {
char data[256];
int len;
//format print
len = snprintf(data,256,"%s%u",ip,port);
//id is just the SHA1 of the ip and port string
SHA1((unsigned char *) data, len,(unsigned char*)id);
/* stringstream ss;
for(int i =0;i<20;i++)
{
ss << id[i];
printf("%02x\n",id[i]);
}*/
return;
}
void bt_lib::print_peer(peer_t* peer) {
int i;
if(peer){
printf("peer: %s:%u ",
inet_ntoa(peer->sockaddr.sin_addr),
peer->port);
printf("id: ");
for(i=0;i<ID_SIZE;i++){
printf("%02x",peer->id[i]);
}
printf("\n");
}
}