| 1 |
/* SPDX-License-Identifier: GPL-2.0-or-later */ |
| 2 |
/* |
| 3 |
* inet_proto.c |
| 4 |
* |
| 5 |
* Authors: Alexey Kuznetsov, <[email protected]> |
| 6 |
*/ |
| 7 |
|
| 8 |
#include <stdio.h> |
| 9 |
#include <stdlib.h> |
| 10 |
#include <unistd.h> |
| 11 |
#include <fcntl.h> |
| 12 |
#include <sys/socket.h> |
| 13 |
#include <netinet/in.h> |
| 14 |
#include <netdb.h> |
| 15 |
#include <string.h> |
| 16 |
|
| 17 |
#include "rt_names.h" |
| 18 |
#include "utils.h" |
| 19 |
|
| 20 |
const char *inet_proto_n2a(int proto, char *buf, int len) |
| 21 |
{ |
| 22 |
static char *ncache; |
| 23 |
static int icache = -1; |
| 24 |
struct protoent *pe; |
| 25 |
|
| 26 |
if (proto == icache) |
| 27 |
return ncache; |
| 28 |
|
| 29 |
pe = getprotobynumber(proto); |
| 30 |
if (pe && !numeric) { |
| 31 |
if (icache != -1) |
| 32 |
free(ncache); |
| 33 |
icache = proto; |
| 34 |
ncache = strdup(pe->p_name); |
| 35 |
strlcpy(buf, pe->p_name, len); |
| 36 |
return buf; |
| 37 |
} |
| 38 |
snprintf(buf, len, "ipproto-%d", proto); |
| 39 |
return buf; |
| 40 |
} |
| 41 |
|
| 42 |
int inet_proto_a2n(const char *buf) |
| 43 |
{ |
| 44 |
static char *ncache; |
| 45 |
static int icache = -1; |
| 46 |
struct protoent *pe; |
| 47 |
__u8 ret; |
| 48 |
|
| 49 |
if (icache != -1 && strcmp(ncache, buf) == 0) |
| 50 |
return icache; |
| 51 |
|
| 52 |
if (!get_u8(&ret, buf, 10)) |
| 53 |
return ret; |
| 54 |
|
| 55 |
pe = getprotobyname(buf); |
| 56 |
if (pe) { |
| 57 |
if (icache != -1) |
| 58 |
free(ncache); |
| 59 |
icache = pe->p_proto; |
| 60 |
ncache = strdup(pe->p_name); |
| 61 |
return pe->p_proto; |
| 62 |
} |
| 63 |
return -1; |
| 64 |
} |