sscanf misbehaving when converting string to IPADDR4

Discussion to talk about software related topics only.
Post Reply
jrh
Posts: 2
Joined: Fri Feb 24, 2017 8:29 am

sscanf misbehaving when converting string to IPADDR4

Post by jrh »

Hi all,

I'm using a MOD5282 and running NBEclipse 2.8.2. I've written the following method to convert a string to an IPADDR4 object:

Code: Select all

bool IP_From_String(char *ip_string, IPADDR4 *ip)
{
	iprintf("Entered IP_From_String. String is: %s\n", ip_string);
	// Check to make sure the format is correct
	//TODO: undefined behavior when values > 255 in ip_string.
	unsigned char ip1, ip2, ip3, ip4;
	DWORD ip_long;
	if(sscanf(ip_string, "%hhu.%hhu.%hhu.%hhu", &ip1, &ip2, &ip3, &ip4) != 4)
	{ // Check for format
		iprintf("received invalid IP: %s\n", ip_string);
		return false;
	}
	else
	{ // everything looks correct
		iprintf("ip: %d.%d.%d.%d\n", ip1, ip2, ip3, ip4);
		ip_long = (ip1 << 24) | (ip2 << 16) | (ip3 << 8) | ip4;
		iprintf("ip_long: %lu\n", ip_long);
	}
	*ip = IPADDR4(ip_long);
	return true;
}
However, when I call the method, I get this output:

Code: Select all

Entered IP_From_String. String is: 192.168.1.20
ip: 0.0.0.0
ip_long: 0
Then the program crashes trying to set *ip.

Any ideas on why sscanf isn't behaving as expected here? The code works with other compilers.
If there's a better way to create an IPADDR4 object from a string, I'd be interested in that as well. I searched the forum but wasn't able to find anything.
sulliwk06
Posts: 118
Joined: Tue Sep 17, 2013 7:14 am

Re: sscanf misbehaving when converting string to IPADDR4

Post by sulliwk06 »

try this, it should be in utils.h

Code: Select all

/*---------------------------------------------------------------**
** Convert a dotted decimal IP to a DWORD in NETWORK byte order. **
**---------------------------------------------------------------*/
IPADDR4 AsciiToIp4( const char *p )
User avatar
TomNB
Posts: 541
Joined: Tue May 10, 2016 8:22 am

Re: sscanf misbehaving when converting string to IPADDR4

Post by TomNB »

IPADDR is an object, not a 32-bit value, so you need to use a function such as sulliwk06 suggested.
jrh
Posts: 2
Joined: Fri Feb 24, 2017 8:29 am

Re: sscanf misbehaving when converting string to IPADDR4

Post by jrh »

Yup that works great. Thanks! When I didn't see a constructor that took a char * I didn't think to look for a misc method elsewhere.
Still don't know why sscanf yields zeros (the code runs fine on another compiler), but it looks like I don't need it anymore.
Post Reply