Logo Search packages:      
Sourcecode: dcgui version File versions  Download package

network.c

/* DCTC - a Direct Connect text clone for Linux
 * Copyright (C) 2001 Eric Prevoteau
 *
 * network.c: Copyright (C) Eric Prevoteau <www@a2pb.gotdns.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
/*
$Id: network.c,v 1.4 2003/12/26 14:35:04 uid68112 Exp $
*/

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <string.h>
#include <net/if.h>
#include <net/route.h>
#include <netdb.h>
#include <ctype.h>
#include <errno.h>
#include <glib.h>

#include "network.h"

/******************************/
/* return the default host IP */
/************************************************************************/
/* the default host IP is the IP of the interface used as default route */
/************************************************************************/
GString *get_default_host_ip(void)
{
      FILE *f;
      char buf[512];

      /* the following script does this: */
      /* 1) extract the interface used by the default route: netstat -rn | grep ^0.0.0.0 | awk '{print $8;} */
      /* 2) obtain the IP of this interface: netstat xxx | fgrep inet | cut -d : -f 2 | awk '{print $1;}' */
      const char *cmd=
#ifndef ROUTE_HAS_GET_DEFAULT
            "/sbin/ifconfig `netstat -rn | awk '/^0.0.0.0/{print$NF}'` | fgrep inet | cut -d : -f 2 | awk '{print $1;}'";
#else
            "/sbin/route -n get default | awk '/local/{print$NF}'";
#endif

      f=popen(cmd,"r");
      if(f==NULL)
      {
            fprintf(stderr,"Unable to create a shell to obtain default IP.\n");
            return NULL;
      }

      if(fgets(buf,sizeof(buf),f)==NULL)
      {
            pclose(f);
            fprintf(stderr,"No default interface found.\n");
            return NULL;
      }

      pclose(f);

      if(strlen(buf)!=0)
      {
            char *t;

            t=buf;
            while( (*t) && ((*t=='.') || (isdigit(*t))) )
                  t++;

            *t='\0';
            return g_string_new(buf);
      }
      else
            return NULL;
}


Generated by  Doxygen 1.6.0   Back to index