Add parse_port function

This commit is contained in:
akp 2023-10-06 23:30:31 +01:00
parent 21b8037bd6
commit cca3460d21
No known key found for this signature in database
GPG key ID: CF8D58F3DEB20755

View file

@ -15,7 +15,7 @@ enum ParseState {
};
// parse_ip parses an IP address line starting at startptr. Returns the ending position of the pointer in line.
// Returns NULL on failure
// Returns NULL on failure.
char* parse_ip(char* startptr, struct IP* ip) {
char* endptr = startptr;
@ -40,6 +40,17 @@ char* parse_ip(char* startptr, struct IP* ip) {
return endptr;
}
// parse_ip parses a port starting at startptr. Returns the ending position of the pointer in line.
// Returns NULL on failure.
char* parse_port(char* startptr, Port* port) {
char* end;
long n = strtol(startptr, &end, 10);
if (n > USHRT_MAX || n < 0)
return NULL;
*port = n;
return end;
}
// parse_rule parses a rule out a string, line. The result is saved to result, which must be allocated by the caller.
// The return value is the ending position of the rule in the string.
char* parse_rule(char line[], struct Rule* result) {
@ -84,14 +95,12 @@ char* parse_rule(char line[], struct Rule* result) {
break;
}
case ParseState_port1: {
char* end;
long n = strtol(line + ptr, &end, 10);
if (n > USHRT_MAX || n < 0)
char* end = parse_port(line + ptr, &result->port.start);
if (end == NULL) {
goto fail;
}
ptr = (int)(end - line);
result->port.start = (Port)(n);
if (line[ptr] == '-') {
ptr += 1;
state = ParseState_port2;
@ -104,14 +113,12 @@ char* parse_rule(char line[], struct Rule* result) {
case ParseState_port2: {
result->port.end = (Port*) malloc(sizeof(Port));
char* end;
long n = strtol(line + ptr, &end, 10);
if (n > USHRT_MAX || n < 0)
char* end = parse_port(line + ptr, result->port.end);
if (end == NULL) {
goto fail;
}
ptr = (int)(end - line);
*(result->port.end) = (Port)(n);
state = ParseState_done;
break;
}