Get IP Address System call
Hello,
Is there a way to get my IP address using a system call of some sort? I've looked at the man page for gethostbyaddr, but there isn't an example how to use it in practice. Thanks for any help. |
This is one method, there are others but less portable:
Code:
#include <stdio.h> |
By the way, I hope its for a UNIX system?
Otherwise for Winblows I dunno. transform socket to Socket maybe :) |
Quote:
It is Linux specific, as it assumes the ethernet interface name is "eth0". It can easily be ported to non-Linux Unix systems though. |
with,
the teletype line that you are currently working and the id from which you are executing parse the /var/adm/wtmpx file you can retrieve the ip address |
nx,
you missed out /usr/include/sys/sockio.h to include SIOCGIFADDR |
jlliagre you're right its maybe not portable to unix as I use ioctl... its been some time I have no access to Unix stations and all these differents implementations.
mmm eth0 is for the example... remove it if you prefer :) Maybe you could post a more-portable solution? Works perfectly for me without any more includes. |
Quote:
Quote:
That's the point here, the OP question was about how retrieving one's own IP address. The problem is that there is no standard way to figure out what is your own network interface, not to mention which one to choose when there are many of them. Quote:
Unfortunately it fails in many cases, if the naming is incorrect (like setting the hostname as a localhost alias) or is dynamic and not updated. Code:
#include <stdio.h> Quote:
BSD and Solaris need this, Linux has SIOCGIFADDR defined in more than one place. |
Quote:
Code:
printf("%s\n", inet_ntoa(*((struct in_addr *)h->h_addr_list[0]))); Code:
printf("%s\n", inet_ntoa(**((struct in_addr **)h->h_addr_list))); |
May be ...
|
Network IP Address of own machine inside C code
One more solution which I found much better than the above one, to know the network IP address of own machine inside C code is as follows:--
FILE *fd; char ip_addr[20]; system("cmd=`/sbin/ifconfig`;y=${cmd#*inet addr:};y=${y%% *};echo $y >ipaddr"); fd = fopen("ipaddr", "r+"); fscanf(fd, "%s", &ip_addr); fclose(fd); fprintf(stderr,"IP Address:%s", ip_addr); This works fine for me. Kindly put your suggestions for above solution. Thanks & Regards, Rodrex. PS: one more solution after such a long time |
Check out getaddrinfo.
|
All times are GMT -5. The time now is 07:26 AM. |