-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbt_lib.c
100 lines (76 loc) · 2.08 KB
/
bt_lib.c
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
#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 <sys/stat.h>
#include <arpa/inet.h>
#include <openssl/sha.h> //hashing pieces
#include "bt_lib.h"
#include "bt_setup.h"
void 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);
return;
}
/**
* init_peer(peer_t * peer, int id, char * ip, unsigned short port) -> int
*
*
* initialize the peer_t structure peer with an id, ip address, and a
* port. Further, it will set up the sockaddr such that a socket
* connection can be more easily established.
*
* Return: 0 on success, negative values on failure. Will exit on bad
* ip address.
*
**/
int 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;
}
/**
* print_peer(peer_t *peer) -> void
*
* print out debug info of a peer
*
**/
void 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");
}
}