This is the code I use for getting the IP address associated to a
certain network interface:
char* get_ipv4_addr(char *ifc) {
int sd=socket(AF_INET,SOCK_STREAM,0);
struct ifreq ifr;
strncpy (ifr.ifr_name,ifc,sizeof(ifr.ifr_name));
struct sockaddr_in *sin = (struct sockaddr_in*) &ifr.ifr_addr;
ioctl(sd,SIOCGIFNAME,&ifr);
ioctl(sd,SIOCGIFADDR,&ifr);
if (!sin->sin_addr.s_addr) return NULL;
else return inet_ntoa(sin->sin_addr);
}
p.s. I see more and more gratuitous and very poorly documented trolls
here. Just think about shutting down this newsgroup instead of
re-routing everybody makes a C-related question to other newsgroups, if
that is not a true ANSI C oriented question. This newsgroup gets very
useless in this case.
<> wrote:
> Hi All,
> Can some one please let me know how to find the ip address of
> a machine within a C program. I've tried gethostbyname() but it uses /
> etc/hosts file which is not I want. I don't even want to extract the
> IP address from ifconfig because it is time consuming. So, can any one
> let me know how can I do this without effecting portability across
> linux flavors (No Windows please).
>
> Awaiting your reply,
>
> Thank you,
> Venu Madhav.
--
-----BEGIN GEEK CODE BLOCK-----
GCS/CM/CC/E/IT/LS/M d-(--) C++++$ UBL++++$ P++++ L+++++$ E--- W+++ w--
PS+++ PE-- Y++ PGP+++ R++ tv-- b++>+++ D+ G>+++ e++>+++++ h* r++ z+++
------END GEEK CODE BLOCK------