Ok. I read the FAQ, but it was fairly vague. I'm trying to create a program that will run until the user inputs 'x'. So this is how I tried to implement it. I also used Salems suggestions on how to pass info from the file into an array to establish my socket. Mind checking over my code and telling me where I should improve on it? I'm used to MUD code, and a lot of this stuff is already in there.
Code:
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
extern int errno;
extern int h_errno;
typedef struct config_data CONFIG_DATA;
struct config_data
{
char *host;
int port;
char *path;
};
void load_config( void )
{
FILE_DATA * fp;
CONFIG_DATA *cData;
int cnt;
char buffer[5000];
if (( fp = fopen("config.txt", "rb" )) == NULL )
{
perror("no config found.");
return 0;
}
for ( cnt = 0; cnt < 3; cnt++ )
{
while ( buffer = fgetc( fp ) ) != EOF )
{
cData->host = str_dup( buffer );
cData->port = str_dup( buffer );
cData->path = str_dup( buffer );
}
}
}
void check_server( void )
{
char buffer[4096];
struct hostent *hostaddr;
int port;
struct protoent *protocol;
int rval;
int sd;
struct sockaddr_in socketaddr;
CONFIG_DATA * cData;
if ( argc[0] != '\0' )
{
printf( "no arguments needed.\n" );
return (EINVAL); /* Invalid argument */
}
/* quick sanity check */
port = atoi( cData->port )
if ( port < 1 || port > 65535 )
{
printf( "client: invalid port number\n" );
return (EINVAL);
}
/*
* Build our socket
*/
protocol = getprotobyname( "tcp" );
if ( !protocol )
{
perror( "getprotobyname()" );
return (errno);
}
sd = socket( PF_INET, SOCK_STREAM, 0 );
if ( sd == -1 )
{
perror( "socket()" );
return (errno);
}
/*
* Setup info about the remote host
*/
memset( &socketaddr, 0, sizeof(socketaddr) );
socketaddr.sin_family = AF_INET;
socketaddr.sin_port = htons( port );
hostaddr = gethostbyname( cData->host );
if ( !hostaddr )
{
fprintf( stderr, "gethostbyname(): %s\n", hstrerror(h_errno) );
return (h_errno);
}
/* copy address from hostaddr to socketaddr */
memcpy( &socketaddr.sin_addr, hostaddr->h_addr, hostaddr->h_length );
/*
* Connect to the host
*/
rval = connect( sd, (struct sockaddr *) &socketaddr, sizeof(socketaddr) );
if ( rval == -1 ) // Servers down, boot it
{
spawnv( P_WAIT, cData->path, argv[0] );
close( sd );
return (0);
}else{
close( sd );
return (0);
}
int main ( int argc, char * argv[])
{
clock_t timer;
load_config( void );
timer = time( );
while ( argv[0] != 'x' )
{
if ( timer == 300 )
{
puts("Checking server.");
check_server( void );
timer = 0;
timer = time( );
}
}
}