For Programmers: Free Programming Magazines  


Home > Archive > Unix Programming > February 2007 > Re: Hai Can anyone give me idea to get the IP address of my camputer through a 'c' pr









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Hai Can anyone give me idea to get the IP address of my camputer through a 'c' pr
Christopher Layne

2007-02-16, 8:08 am

sunny wrote:

> Hai,
>
> Anybody can give me idea how to get the ip address of my machine
> through a cprogram with out using the socket programming. Is there
> any
> system call to get the ip address of my machine that will be used in
> the c program to display the IP address of my machine.
>
>
> Regards,
> Sunny


Not going to happen without sockets. Also not going to possibly work on all
OSes.

#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>

extern int if_populate(char **dest, size_t ne, in_addr_t mask)
{
struct ifconf ifc;
struct ifreq *ifr;
struct sockaddr_in *sa;
struct in_addr addr;
char l_addr[256];
char *tmp;
int s;
unsigned int i, y;

ifc.ifc_len = sizeof(l_addr);
ifc.ifc_buf = l_addr;

s = socket(AF_INET, SOCK_STREAM, 0);
if ((ioctl(s, SIOCGIFCONF, &ifc)) == -1) {
perror("ioctl");
return -1;
}
close(s);

for (i = y = 0; i < (ifc.ifc_len / sizeof(struct ifreq)); i++) {
ifr = ifc.ifc_req + i;
sa = (struct sockaddr_in *)&ifr->ifr_addr;
addr.s_addr = sa->sin_addr.s_addr;

if ((ntohl(addr.s_addr) & mask) == mask && y < ne) {
tmp = inet_ntoa(addr);
dest[y] = malloc(strlen(tmp) + 1);
if (dest[y] == NULL)
abort();
strcpy(dest[y], tmp);
y++;
}
}

return y;
}

int main(int argc, char **argv)
{
char *sa_tab[4];
size_t i;

i = if_populate(sa_tab, sizeof sa_tab / sizeof *sa_tab,
inet_network(argc < 2 ? "0.0.0.0" : argv[1]));

while (i--)
fprintf(stdout, "%s\n", sa_tab[i]);

return 0;
}
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com