trafgen: eth: Add setting next protocol id
[netsniff-ng.git] / str.c
blobcfee03f3337d952aa8ca78524f1c32f5d1b9747f
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010 Daniel Borkmann.
4 * Subject to the GPL, version 2.
5 */
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdarg.h>
10 #include <arpa/inet.h>
12 #include "str.h"
13 #include "die.h"
14 #include "xmalloc.h"
16 size_t strlcpy(char *dest, const char *src, size_t size)
18 size_t ret = strlen(src);
20 if (size) {
21 size_t len = (ret >= size) ? size - 1 : ret;
23 memcpy(dest, src, len);
24 dest[len] = '\0';
27 return ret;
30 static inline int vslprintf(char *dst, size_t size, const char *fmt, va_list ap)
32 int ret;
34 ret = vsnprintf(dst, size, fmt, ap);
35 dst[size - 1] = '\0';
37 return ret;
40 int slprintf(char *dst, size_t size, const char *fmt, ...)
42 int ret;
43 va_list ap;
45 va_start(ap, fmt);
46 ret = vslprintf(dst, size, fmt, ap);
47 va_end(ap);
49 return ret;
52 int slprintf_nocheck(char *dst, size_t size, const char *fmt, ...)
54 int ret;
55 va_list ap;
57 va_start(ap, fmt);
58 ret = vslprintf(dst, size, fmt, ap);
59 va_end(ap);
61 return ret;
64 noinline void *xmemset(void *s, int c, size_t n)
66 size_t i;
67 uint8_t *ptr = s;
69 for (i = 0; i < n; ++i)
70 ptr[i] = (uint8_t) c;
72 return ptr;
75 char *strtrim_right(char *p, char c)
77 char *end;
78 size_t len;
80 len = strlen(p);
81 while (*p && len) {
82 end = p + len - 1;
83 if (c == *end)
84 *end = 0;
85 else
86 break;
87 len = strlen(p);
90 return p;
93 char *argv2str(int startind, int argc, char **argv)
95 off_t offset = 0;
96 char *str = NULL;
97 int ret, i;
99 for (i = startind; i < argc; ++i) {
100 size_t alen = strlen(argv[i]) + 2;
101 size_t slen = str ? strlen(str) : 0;
103 str = xrealloc(str, slen + alen);
104 ret = slprintf(str + offset, strlen(argv[i]) + 2, "%s ", argv[i]);
105 if (ret < 0)
106 panic("Cannot concatenate string!\n");
107 else
108 offset += ret;
111 return str;
114 char **argv_insert(char **argv, size_t *count, const char *str)
116 argv = xrealloc(argv, (*count + 2) * sizeof(char *));
117 argv[*count] = str ? xstrdup(str) : xstrdup("");
118 argv[*count + 1] = NULL;
120 *count += 1;
121 return argv;
124 void argv_free(char **argv)
126 char **tmp = argv;
128 for (; argv && *argv; argv++)
129 free(*argv);
131 free(tmp);
134 int str2mac(const char *str, uint8_t *mac, size_t len)
136 int i, count;
137 unsigned int tmp[6];
139 if (!str)
140 return -EINVAL;
141 if (len < 6)
142 return -ENOSPC;
144 count = sscanf(str, "%02X:%02X:%02X:%02X:%02X:%02X",
145 &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]);
147 if (errno || count != 6)
148 count = sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
149 &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]);
151 if (count != 6)
152 return -EINVAL;
153 if (errno)
154 return -errno;
156 for (i = 0; i < 6; i++)
157 mac[i] = (uint8_t)tmp[i];
159 return 0;