How can I convert an IP address to a char string?

for everything else
Post Reply
Ron Neal
Posts: 17
Joined: Tue May 05, 2009 1:20 pm

How can I convert an IP address to a char string?

Post by Ron Neal »

I need to convert an IP address to a char string (xxx.xxx.xxx.xxx) so that I can send it to an html page using "writesafestring". I don't see that "Showip" can be made to work for this situation.

Thanks,

Ron Neal
User avatar
tod
Posts: 587
Joined: Sat Apr 26, 2008 8:27 am
Location: Southern California
Contact:

Re: How can I convert an IP address to a char string?

Post by tod »

There are probably many ways. Here is one use the old C sprintf (instead of iostreams which are currently causing me a problem). This came from my namespace NNbSysUtils so you will need to strip that off and put the method wherever you deem suitable.

Code: Select all

//===========================================================================
// IpToAscii()
// Convert an IP Address to an ASCII dotted decimal string t
// @param ip the netburner's representation of an IP Address
// @param retAscii a pointer to the string where we will put the IP address
//===========================================================================
void NNbSysUtils::IpToAscii( IPADDR ip, char* retAscii)
{
  //cast the longint to byte and use array references to get to each byte
  //to easily convert one octet at a time
  uint8_t* ipb= reinterpret_cast<uint8_t*>(&ip);
  siprintf(retAscii,"%03d.%03d.%03d.%03d",ipb[0],ipb[1],ipb[2],ipb[3]);
}
Ridgeglider
Posts: 513
Joined: Sat Apr 26, 2008 7:14 am

Re: How can I convert an IP address to a char string?

Post by Ridgeglider »

Just modify the code for ShowIP :

Code: Select all

void ShowIP( IPADDR  ia )
{
   PBYTE ipb = ( PBYTE ) & ia;
   iprintf( "%d.%d.%d.%d", ( int ) ipb[0], ( int ) ipb[1], ( int ) ipb[2], ( int ) ipb[3] );
}
Instead of using printf, load a buffer with siprintf, (or safer) with snprintf then write the buffer.
User avatar
pbreed
Posts: 1080
Joined: Thu Apr 24, 2008 3:58 pm

Re: How can I convert an IP address to a char string?

Post by pbreed »

There are lots of ways to do things....
Another way to do it using the HTML variable functions,
the functions are designed for use on a web page, but can also be used to write human readable stuff to and fd/socket

#include <htmlfiles.h>


WriteHtmlVariable(my_socket_or_fd,IPCAST(ip));

If you want to you can use ANY of the WriteHtmlVariable functions:


void WriteHtmlVariable(int fd, char c);
void WriteHtmlVariable(int fd, int i);
void WriteHtmlVariable(int fd, short i);
void WriteHtmlVariable(int fd, long i);
void WriteHtmlVariable(int fd, BYTE b);
void WriteHtmlVariable(int fd, WORD w);
void WriteHtmlVariable(int fd, unsigned long dw);
void WriteHtmlVariable(int fd, const char *);
void WriteHtmlVariable(int fd, MACADR m);
Post Reply