long ip2long( char *ip )
{
long ip2long = 0;
char B1[4], B2[4], B3[4], B4[4];
int D1, D2, D3, D4 = 0;
sscanf(ip, "%s.%s.%s.%s", B1, B2, B3, B4);
D1 = atoi(B1);
D2 = atoi(B2);
D3 = atoi(B3);
D4 = atoi(B4);
if(D1 > 255 || D2 > 255 || D3 > 255 || D4 > 255)
return 0;
ip2long = D1*256*256*256+D2*256*256+D3*256+D4;
return ip2long;
}
input data: 127.1.1.2
Why D1 == 127, but D2, D3 and D4 == 0?
— UPDATE —
Now code is
unsigned long ip2long( char *ip )
{
unsigned long ip2long = 0;
unsigned int D1, D2, D3, D4 = 0;
sscanf(ip, "%u.%u.%u.%u", &D1, &D2, &D3, &D4);
if(D1 > 255 || D2 > 255 || D3 > 255 || D4 > 255)
return 0;
ip2long = D1*256*256*256+D2*256*256+D3*256+D4;
return ip2long;
}
Di is ok, but there are another troubles: result for 127.1.1.2 is 2130772226 instead of 2130772225 and result for 195.98.157.132 is -1016947324…
Why?
— Update 2 —
Thats ok, there was %d instread %u.
Kornel Kisielewicz thank you for telling about inet_addr function 🙂
PS sorry for my bad english =\
Question closed.
As fizzer notes,
%sconsumes the entire string – in this case dangerously copying it past the end of S1. There would have been a big clue if the sscanf() result had been compared to 4! Don’t assume things will work, especially when parsing input from outside the program.atoiignores trailing garbage, so even with the%[^.]string format which will stop at a period it will process garbage values like192,3.2x.3.1by ignoring,3andx.fizzer’s suggestion of
("...%d...", &D1...)is a good start, but you must still compare the result to 4, otherwise invalid strings like “hello” would simply leave D1, D2, D3 and D4 unchanged. Negative values would be accepted. Note that only D4 is set to 0 – other values are not affected by the trailing= 0on that line and may contain old garbage values form the stack which may or may not get through the later check against 255.Summarily: