diff --git a/include/multiaddr/multiaddr.h b/include/multiaddr/multiaddr.h index d03baf1..4a412ef 100644 --- a/include/multiaddr/multiaddr.h +++ b/include/multiaddr/multiaddr.h @@ -80,4 +80,11 @@ int multiaddress_get_ip_address(const struct MultiAddress* in, char** ip); */ int multiaddress_get_ip_port(const struct MultiAddress* in); +/** + * Pulls the peer ID out of a multiaddress struct + * @param in the MultiAddress + * @returns a pointer to the peer id string, or NULL + */ +char* multiaddress_get_peer_id(const struct MultiAddress* in); + #endif diff --git a/multiaddr.c b/multiaddr.c index cea946e..17ee7ed 100644 --- a/multiaddr.c +++ b/multiaddr.c @@ -129,7 +129,7 @@ int multiaddress_get_ip_address(const struct MultiAddress* in, char** ip) { *ip = malloc(strlen(str) + 1); strcpy(*ip, str); free(str); - return 0; + return 1; } /*** @@ -155,6 +155,13 @@ int multiaddress_get_ip_port(const struct MultiAddress* in) { return atoi(str); } +char* multiaddress_get_peer_id(const struct MultiAddress* in) { + char* ptr = strstr(in->string, "/ipfs/"); + if (ptr == NULL) + return NULL; + return &ptr[6]; +} + void multiaddress_free(struct MultiAddress* in) { if (in != NULL) { if (in->bytes != NULL) @@ -169,8 +176,7 @@ void multiaddress_free(struct MultiAddress* in) { /** * Copy a multiaddress from one memory location to another * @param in the source - * @param out the destination. NOTE: memory for out should be preallocated - * @returns true(1) on success, otherwise false(0) + * @returns the new struct MultiAddress or NULL if there was a problem (i.e. out of memory) */ struct MultiAddress* multiaddress_copy(const struct MultiAddress* in) { struct MultiAddress* out = NULL; diff --git a/test_multiaddr.h b/test_multiaddr.h index 9a2e68e..4356f81 100644 --- a/test_multiaddr.h +++ b/test_multiaddr.h @@ -92,3 +92,26 @@ int test_multiaddr_utils() { return 1; } +int test_multiaddr_peer_id() { + char* orig_address = "QmKhhKHkjhkjhKjhiuhKJh"; + char full_string[255]; + char* result = NULL; + int retVal = 0; + struct MultiAddress* addr; + + sprintf(full_string, "/ip4/127.0.0.1/tcp/4001/ipfs/%s", orig_address); + + addr = multiaddress_new_from_string(full_string); + + result = multiaddress_get_peer_id(addr); + + if (result == NULL || strncmp(result, orig_address, strlen(orig_address)) != 0) + goto exit; + + retVal = 1; + exit: + if (addr != NULL) + multiaddress_free(addr); + return retVal; +} + diff --git a/testing.c b/testing.c index d77c42d..a6da84c 100644 --- a/testing.c +++ b/testing.c @@ -7,7 +7,8 @@ const char* names[] = { "test_full", "test_hex_to_var", "test_int_to_hex", - "test_multiaddr_utils" + "test_multiaddr_utils", + "test_multiaddr_peer_id" }; int (*funcs[])(void) = { @@ -15,7 +16,8 @@ int (*funcs[])(void) = { test_full, test_hex_to_var, test_int_to_hex, - test_multiaddr_utils + test_multiaddr_utils, + test_multiaddr_peer_id }; int testit(const char* name, int (*func)(void)) {