This is the mail archive of the
cygwin
mailing list for the Cygwin project.
hot to get IP from shell -> C solution
- From: "electa" <electabuzz at katamail dot com>
- To: cygwin at cygwin dot com
- Date: Thu, 22 Apr 2004 16:57:13 +0200
- Subject: hot to get IP from shell -> C solution
/* 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/