I have to parse this string in C:
XFR 3 NS 207.46.106.118:1863 0 207.46.104.20:1863\r\n
And be able to get the 207.46.106.118
part and 1863
part (the first ip address).
I know I could go char by char and eventually find my way through it, but what's the easiest way to get this information, given that the IP address in the string could change to a different format (with less digits)?
You can use
sscanf()
from the C standard lib. Here's an example of how to get the ip and port as strings, assuming the part in front of the address is constant:The important parts of the format strings are the scanset patterns
%15[0-9.]
and%5[0-9]
, which will match a string of at most 15 characters composed of digits or dots (ie ip addresses won't be checked for well-formedness) and a string of at most 5 digits respectively (which means invalid port numbers above 2^16 - 1 will slip through).