huangcm
2024-12-18 9d29be7f7249789d6ffd0440067187a9f040c2cd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <linux/mpls.h>
 
#include "utils.h"
 
static const char *mpls_ntop1(const struct mpls_label *addr, char *buf, size_t buflen)
{
   size_t destlen = buflen;
   char *dest = buf;
   int count = 0;
 
   while (1) {
       uint32_t entry = ntohl(addr[count++].entry);
       uint32_t label = (entry & MPLS_LS_LABEL_MASK) >> MPLS_LS_LABEL_SHIFT;
       int len = snprintf(dest, destlen, "%u", label);
 
       if (len >= destlen)
           break;
 
       /* Is this the end? */
       if (entry & MPLS_LS_S_MASK)
           return buf;
 
       dest += len;
       destlen -= len;
       if (destlen) {
           *dest = '/';
           dest++;
           destlen--;
       }
   }
   errno = -E2BIG;
   return NULL;
}
 
const char *mpls_ntop(int af, const void *addr, char *buf, size_t buflen)
{
   switch(af) {
   case AF_MPLS:
       errno = 0;
       return mpls_ntop1((struct mpls_label *)addr, buf, buflen);
   default:
       errno = EAFNOSUPPORT;
   }
 
   return NULL;
}