Skip to content
Snippets Groups Projects
utils.h 2.40 KiB
#ifndef EASYUTILS_H
#define EASYUTILS_H

#include <stdint.h>
#include <stdbool.h>
#include <linux/types.h>

#ifdef __cplusplus
extern "C" {
#endif

#if 0
#if __GNUC__ >= 4
# define LIBEASY_API	__attribute__((visibility("default")))
#else
# define LIBEASY_API
#endif
#endif

/** Convert hex string to byte array
 *
 * For example:
 * "001122334455" --> {0x00, 0x11, 0x22, 0x33, 0x44, 0x55}
 *
 * @param[in] str hex string.
 * @param[in] len string length of the hex string.
 * @param[out] bytes output buffer to write the converted hex string.
 * @return byte array of the converted hex string.
 */
LIBEASY_API extern uint8_t *strtob(char *str, int len, uint8_t *bytes);


/** Convert byte array to hex string
 *
 * For example:
 * {0x00, 0x11, 0x22, 0x33, 0x44, 0x55} --> "001122334455"
 *
 * @param[in] bytes byte array.
 * @param[in] len length of the byte array.
 * @param[out] str output buffer to write the hex string.
 * @return hex string.
 */
LIBEASY_API extern char *btostr(uint8_t *bytes, int len, char *str);


/** Convert macaddress from ':' separated string to byte array
 *
 * For example:
 * "00:11:22:33:44:55" --> {0x00, 0x11, 0x22, 0x33, 0x44, 0x55}
 *
 * @param[in] macstr mac address string.
 * @param[out] mac output buffer to write the converted macstr.
 * @return output byte array of the converted macstr.
 */
LIBEASY_API extern uint8_t *hwaddr_aton(const char *macstr, uint8_t *mac);


/** Convert macaddress from byte array to ':' separated string
 *
 * For example:
 * {0x00, 0x11, 0x22, 0x33, 0x44, 0x55} --> "00:11:22:33:44:55"
 *
 * @param[in] mac macaddress byte array.
 * @param[out] macstr mac address string in ':' sepearted format.
 * @return output macaddress string in ':' separated format.
 */
LIBEASY_API extern char *hwaddr_ntoa(const uint8_t *mac, char *macstr);

static inline int hwaddr_equal(const uint8_t *a, const uint8_t *b)
{
	return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2])
		| (a[3] ^ b[3]) | (a[4] ^ b[4]) | (a[5] ^ b[5])) == 0;
}

static inline bool hwaddr_is_zero(const uint8_t *a)
{
	return (a[0] | a[1] | a[2] | a[3] | a[4] | a[5]) == 0;
}

static inline bool hwaddr_is_bcast(const uint8_t *a)
{
	return (a[0] & a[1] & a[2] & a[3] & a[4] & a[5]) == 0xff;
}

/* install a signal handler */
LIBEASY_API extern int set_sighandler(int sig, void (*handler)(int));

/* uninstall a signal handler */
LIBEASY_API extern int unset_sighandler(int sig);

#ifdef __cplusplus
}
#endif

#endif /* EASYUTILS_H */