TCLUG Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [TCLUG:12705] A Little C Question



On Fri, 21 Jan 2000, Jonathan Kline wrote:

> I have the line #define base ='206.191.221.' above the function main in a
> c file.  later on I create a loop and assign the remainder of the IP
> address, So it selects a number, Anyone know how to combine base with the
> final number?  This final IP has to be passed to a function
> Any ideas?  Thanks.
> 

First off, don't use #define for this.  Use something like this in a
header file if you need it hard coded.

static char base[] = "206.191.221.";

You need a function to turn an int to a string (null terminated array),
call it char * int_to_str(int);

It would be better if it were a command line option.  Then do something
like this:

char * addr = malloc(16); /* xxx.xxx.xxx.xxx\0 */
strcpy(addr,base);
strcpy(&addr[12],int_to_str(host));

it would actually be better to figure out how big base and host are, and
use strncpy, returning errors where appropriate to avoid buffer
overflows.  See the man pages for malloc, strcpy, strlen, etc.

-Chris