delorie.com/archives/browse.cgi   search  
Mail Archives: cygwin/2004/04/22/10:57:25

Mailing-List: contact cygwin-help AT cygwin DOT com; run by ezmlm
List-Subscribe: <mailto:cygwin-subscribe AT cygwin DOT com>
List-Archive: <http://sources.redhat.com/ml/cygwin/>
List-Post: <mailto:cygwin AT cygwin DOT com>
List-Help: <mailto:cygwin-help AT cygwin DOT com>, <http://sources.redhat.com/ml/#faqs>
Sender: cygwin-owner AT cygwin DOT com
Mail-Followup-To: cygwin AT cygwin DOT com
Delivered-To: mailing list cygwin AT cygwin DOT com
To: cygwin AT cygwin DOT com
From: "electa" <electabuzz AT katamail DOT com>
Subject: hot to get IP from shell -> C solution
Date: Thu, 22 Apr 2004 16:57:13 +0200
Lines: 103
Message-ID: <c68mf0$l50$1@sea.gmane.org>
X-Complaints-To: usenet AT sea DOT gmane DOT org
X-Gmane-NNTP-Posting-Host: n33d195.cs.unibo.it
X-Newsreader: Microsoft Outlook Express 6.00.2800.1158

/* little utility to get the IP address of the machine

- prints the IP address in triple-dotted form xxx.yyy.zzz.www,

or nothing if can't get it.

- this code is a fragment from EpidEm code.

*/

#include <stdio.h>

#include <arpa/inet.h>

#include <netinet/in.h>

#include <unistd.h>

#include <netdb.h>

/*

Returns the IP address of this host.

- if host have more than 1 IP, only 1 (the first) is returned.

- return is in network byte order

- thanks to Doct. Ghini (www.cs.unibo.it/~ghini)

return: 0 if unsuccessful, the IP otherwise

*/

in_addr_t get_my_IP()

{

/* have you ever seen a hostname longer than a screen (80cols)?*/

char name[80]; /*store my hostname*/

struct hostent * hostent_ptr;

int ret;

ret = gethostname (name, 80);

if(ret == -1) {

/*printf ("ERROR gethostname() failed, Errno=%d \nDescription: %s\n", errno,

strerror(errno));*/

return 0;

}


hostent_ptr = gethostbyname(name);


if(hostent_ptr == NULL)

{

/*printf ("ERROR gethostbyname() failed, h_errno=%d \nDescription: %s\n",
h_errno, hstrerror(h_errno));*/

return 0;

}

/*h_addr_list contains IPs of this host in network byte order */

return ((struct in_addr *)hostent_ptr->h_addr_list[0])->s_addr; /*get the
first IP.*/

}

int main()

{

in_addr_t my_ip = get_my_IP();

if (my_ip != 0)

{

struct in_addr temp;

temp.s_addr = my_ip;

printf("%s\n", inet_ntoa(temp));

}

return 0;

}




--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Problem reports:       http://cygwin.com/problems.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019