2
* conversion from protocol/port string to protocol and port
3
* Copyright (C) 2002 Mario Strasser <mast@gmx.net>,
4
* Zuercher Hochschule Winterthur,
6
* This program is free software; you can redistribute it and/or modify it
7
* under the terms of the GNU General Public License as published by the
8
* Free Software Foundation; either version 2 of the License, or (at your
9
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11
* This program is distributed in the hope that it will be useful, but
12
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16
* RCSID $Id: ttoprotoport.c,v 1.1.8.1 2004/03/21 05:23:31 mcr Exp $
23
* ttoprotoport - converts from protocol/port string to protocol and port
26
ttoprotoport(src, src_len, proto, port)
27
char *src; /* input string */
28
size_t src_len; /* length of input string, use strlen() if 0 */
29
u_int8_t *proto; /* extracted protocol number */
30
u_int16_t *port; /* extracted port number if it exists */
32
char *end, *service_name;
36
struct protoent *protocol;
37
struct servent *service;
39
/* get the length of the string */
40
if (!src_len) src_len = strlen(src);
42
/* locate delimiter '/' between protocol and port */
43
end = strchr(src, '/');
45
proto_len = end - src;
46
service_name = end + 1;
49
service_name = src + src_len;
52
/* copy protocol name*/
53
memset(proto_name, '\0', sizeof(proto_name));
54
memcpy(proto_name, src, proto_len);
56
/* extract protocol by trying to resolve it by name */
57
protocol = getprotobyname(proto_name);
58
if (protocol != NULL) {
59
*proto = protocol->p_proto;
61
else /* failed, now try it by number */
63
l = strtol(proto_name, &end, 0);
65
if (*proto_name && *end)
66
return "<protocol> is neither a number nor a valid name";
68
if (l < 0 || l > 0xff)
69
return "<protocol> must be between 0 and 255";
74
/* extract port by trying to resolve it by name */
75
service = getservbyname(service_name, NULL);
76
if (service != NULL) {
77
*port = ntohs(service->s_port);
79
else /* failed, now try it by number */
81
l = strtol(service_name, &end, 0);
83
if (*service_name && *end)
84
return "<port> is neither a number nor a valid name";
86
if (l < 0 || l > 0xffff)
87
return "<port> must be between 0 and 65535";