| 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;
}
|