ucspi-tcp6 1.13.02
ucspi-tcp6
Loading...
Searching...
No Matches
ip4_bit.c
Go to the documentation of this file.
1/***
2 @file ip4_bit.c
3 @author Jens Wehrenbrecht, feh
4 @funcs ip4_bitstring, bitstring_ip4
5*/
6#include "ip.h"
7#include "byte.h"
8#include "scan.h"
9#include "str.h"
10#include "fmt.h"
11#include "ip_bit.h"
12
13#define BITSUBSTITUTION
14
15static char strnum[FMT_ULONG];
16
26int ip4_bitstring(stralloc *ip4string, char *ip, unsigned int prefix)
27{
28 int i, j;
29 char ip4[4];
30 int count = 0;
31 unsigned char number;
32#ifdef BITSUBSTITUTION
33 const char *letterarray = "abcdefghijklmnopqrstuvwxyz123456";
34#endif
35
36 if (!stralloc_copys(ip4string,"")) return -1;
37 if (!stralloc_readyplus(ip4string,32)) return -1;
38 ip4_scan(ip,ip4);
39
40 for (i = 0; i < 4; i++) {
41 number = (unsigned char) ip4[i];
42 for (j = 7; j >= 0; j--) {
43 if (number & (1<<j)) {
44#ifdef BITSUBSTITUTION
45 if (!stralloc_catb(ip4string,letterarray + count,1)) return -1;
46#else
47 if (!stralloc_cats(ip4string,"1")) return -1;
48#endif
49 } else {
50 if (!stralloc_cats(ip4string,"0")) return -1;
51 }
52 count++;
53 prefix--;
54 if (prefix == 0) return 0;
55 }
56 }
57
58 return 1;
59}
60
69int bitstring_ip4(stralloc *ip4addr, stralloc *ip4string)
70{
71 int j;
72 int num = 0;
73 int value = 256;
74 int prefix;
75
76 if (!stralloc_copys(ip4addr,"")) return -1;
77 prefix = ip4string->len - 1;
78
79 if (prefix <= 0) return 1;
80 if (prefix <= 1 || prefix > 32) return 1;
81
82 for (j = 1; j <= prefix; j++) {
83 if (ip4string->s[j] != '0') {
84 num += (value/2);
85 value /= 2;
86 } else
87 value /= 2;
88 if (j % 8 == 0 || j == prefix) {
89 if (!stralloc_catb(ip4addr,strnum,fmt_ulong(strnum,num))) return -1;
90 if (j < 32) if (!stralloc_cats(ip4addr,".")) return -1;
91 num = 0;
92 value = 256;
93 }
94 }
95
96 if (!stralloc_cats(ip4addr,"/")) return -1;
97 if (!stralloc_catb(ip4addr,strnum,fmt_ulong(strnum,prefix))) return -1;
98 if (!stralloc_0(ip4addr)) return -1;
99
100 return 0;
101}
int ip4_bitstring(stralloc *ip4string, char *ip, unsigned int prefix)
Definition: ip4_bit.c:26
int bitstring_ip4(stralloc *ip4addr, stralloc *ip4string)
Definition: ip4_bit.c:69