Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

inet_ntoa problem

Status
Not open for further replies.

ramg75

Programmer
Apr 9, 2002
1
IN
inet_ntoa () library call is often used to print the IP address in a dotted decimal format. Care should be taken while using two or more inet_ntoa () library calls in a single statement for example

-----------
#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>

struct inaddr ipaddr;
struct inaddr maskaddr;

ipaddr.s_addr = 0x01020304;
maskaddr.s_addr = 0xffffffff;

sprintf (buff, `IP Addr %s\t Mask %s\n`,
inet_ntoa (ipaddr),
inet_ntoa (maskaddr));

When we print the content of the `buff` we will be surprised to see the `ipaddr` is repeated two times (`IP Addr 1.2.3.4 Mask 1.2.3.4`). This is because the inet_ntoa () returns the pointer to a string. Successive calls OVERWRITES the existing memory. To avoid this inet_ntoa () call should be used one by one and not in the same line. Correct usage is
----------------
sprintf (buff, `%s`, inet_ntoa (ipaddr));
sprintf (buff+4, `%s`, inet_ntoa (maskaddr));
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top