Mailing-List: contact cygwin-help AT cygwin DOT com; run by ezmlm List-Subscribe: List-Archive: List-Post: List-Help: , 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" Subject: hot to get IP from shell -> C solution Date: Thu, 22 Apr 2004 16:57:13 +0200 Lines: 103 Message-ID: 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 #include #include #include #include /* 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/