tAdd functions to bind on local port - libeech - bittorrent library
(HTM) git clone git://z3bra.org/libeech.git
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit 981d390989a1c9f78eccad8da43cf1cb3c7a6c42
(DIR) parent 8afdae6d82a60416d382d93de7d59d18b5adb488
(HTM) Author: Willy Goiffon <dev@z3bra.org>
Date: Tue, 24 Mar 2020 13:32:15 +0100
Add functions to bind on local port
Diffstat:
M libeech.c | 47 +++++++++++++++++++++++++++++++
M libeech.h | 1 +
2 files changed, 48 insertions(+), 0 deletions(-)
---
(DIR) diff --git a/libeech.c b/libeech.c
t@@ -49,6 +49,9 @@ static int bit(char *, long);
static char *setbit(char *, long);
static char *clrbit(char *, long);
+/* helpers for network operations */
+struct in_addr * getinetaddr(char *);
+
/* helpers to retrieve attributes from metadata */
static char * peerid();
static long torrentsize(struct torrent *);
t@@ -129,6 +132,19 @@ clrbit(char *bits, long off)
return bits;
}
+struct in_addr *
+getinetaddr(char *hostname)
+{
+ struct hostent *he;
+
+ if (!(he = gethostbyname(hostname))) {
+ herror(hostname);
+ return NULL;
+ }
+
+ return ((struct in_addr **)he->h_addr_list)[0];
+}
+
/* generate a random peer ID */
char *
peerid()
t@@ -1164,6 +1180,37 @@ glch_addpeer(struct torrent *t, struct peer *p, char *host, int port)
}
/*
+ * bind on a local port to listen for incoming connections
+ *
+ * RETURN VALUE: the socket fd on successful bind, -1 otherwise
+ */
+int
+glch_bind(char *host, int port)
+{
+ int fd;
+ struct in_addr *h;
+ struct sockaddr_in s;
+
+ if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
+ return -1;
+
+ h = getinetaddr(host);
+
+ memset(&s, 0, sizeof(s));
+ s.sin_family = AF_INET;
+ s.sin_addr.s_addr = h->s_addr;
+ s.sin_port = htons(port);
+
+ if (bind(fd, (struct sockaddr *)&s, sizeof(s)) < 0)
+ return -1;
+
+ if (listen(fd, 10) < 0)
+ return -1;
+
+ return fd;
+}
+
+/*
* Perform one network iteration with all the peers, or timeout if
* no one replies
*/
(DIR) diff --git a/libeech.h b/libeech.h
t@@ -68,5 +68,6 @@ struct torrent {
int glch_loadtorrent(struct torrent *, char *, size_t);
int glch_addpeer(struct torrent *, struct peer *, char *, int);
+int glch_bind(char *, int);
int glch_leech(struct torrent *, int);
long glch_piececount(struct torrent *);