Marcus Brinkmann <[EMAIL PROTECTED]> writes: > It would be good if people who solved a common problem they encountered in > porting an application would send me a small html text I can include on this > page.
Here are two examples of fixing MAXHOSTNAME problems:
<p>
If the code you want to port, uses a static buffer of size <em>MAXHOSTNAME</em>
<pre>
char hostname[MAXHOSTNAME];
...
if (gethostname(hostname, MAXHOSTNAME) < 0) {
/* error handling */
...
}
</pre>
you should replace that with a dynamic buffer that is expanded until
the hostname fits.
<pre>
char *hostname;
size_t hostname_size = 100;
...
if ((hostname = (char *)malloc(hostname_size)) == NULL) {
/* handle out of memory */
...
}
while (gethostname(hostname, hostname_size) < 0) {
if (errno != ENAMETOOLONG) {
/* error handling */
...
break;
}
/* else: try again with bigger buffer */
hostname_size <<= 1;
if ((hostname = (char *)realloc(hostname, hostname_size)) == NULL) {
/* handle out of memory */
...
break;
}
}
...
/* don't forget to free hostname on all return paths! */
free(hostname);
</pre>
</p>
<p>
Another usage of <em>MAXHOSTNAME</em> is for buffers filled with info
from <em>gethostby...()</em>:
<pre>
struct hostent *ent;
char peer[MAXHOSTNAME];
...
/* gethostbyaddr or similar is used to fill ent */
...
strcpy(peer, ent->h_name);
</pre>
this should be also changed to dynamic allocation:
<pre>
struct hostent *ent;
char *peer;
...
/* gethostbyaddr or similar is used to fill ent */
...
if ((peer = strdup(ent->h_name)) == NULL) {
/* handle out of memory */
...
}
...
/* again, don't forget to free peer in any case */
free(peer);
</pre>
</p>
--
Robbe
signature.ng
Description: PGP signature

