1 /* 2 * inet_proto.c 3 * 4 * This program is free software; you can redistribute it and/or 5 * modify it under the terms of the GNU General Public License 6 * as published by the Free Software Foundation; either version 7 * 2 of the License, or (at your option) any later version. 8 * 9 * Authors: Alexey Kuznetsov, <kuznet (at) ms2.inr.ac.ru> 10 * 11 */ 12 13 #include <stdio.h> 14 #include <stdlib.h> 15 #include <unistd.h> 16 #include <syslog.h> 17 #include <fcntl.h> 18 #include <sys/socket.h> 19 #include <netinet/in.h> 20 #include <netdb.h> 21 #include <string.h> 22 23 #include "rt_names.h" 24 #include "utils.h" 25 26 const char *inet_proto_n2a(int proto, char *buf, int len) 27 { 28 static char *ncache; 29 static int icache = -1; 30 struct protoent *pe; 31 32 if (proto == icache) 33 return ncache; 34 35 pe = getprotobynumber(proto); 36 if (pe) { 37 if (icache != -1) 38 free(ncache); 39 icache = proto; 40 ncache = strdup(pe->p_name); 41 strlcpy(buf, pe->p_name, len); 42 return buf; 43 } 44 snprintf(buf, len, "ipproto-%d", proto); 45 return buf; 46 } 47 48 int inet_proto_a2n(const char *buf) 49 { 50 static char *ncache; 51 static int icache = -1; 52 struct protoent *pe; 53 __u8 ret; 54 55 if (icache != -1 && strcmp(ncache, buf) == 0) 56 return icache; 57 58 if (!get_u8(&ret, buf, 10)) 59 return ret; 60 61 pe = getprotobyname(buf); 62 if (pe) { 63 if (icache != -1) 64 free(ncache); 65 icache = pe->p_proto; 66 ncache = strdup(pe->p_name); 67 return pe->p_proto; 68 } 69 return -1; 70 } 71