2008年3月21日 星期五

Get IP address / Netmask / Broadcast C code

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <ifaddrs.h>
#include <string.h>

int printLocalIps()
{
struct ifaddrs *ifa = NULL, *ifp = NULL;

if (getifaddrs (&ifp) < 0)
{
perror ("getifaddrs");
return 1;
}

for (ifa = ifp; ifa; ifa = ifa->ifa_next)
{
char ip[NI_MAXHOST];
socklen_t salen;

if (ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in *sin = (struct sockaddr_in *)(ifa->ifa_addr);
salen = sizeof (struct sockaddr_in);

/*printf("%s : %s\n", ifa->ifa_name, inet_ntoa(sin->sin_addr)); */

} else if (ifa->ifa_addr->sa_family == AF_INET6)
/*salen = sizeof (struct sockaddr_in6);*/
continue;
else
continue;
printf("<---------->\n");
printf("%s :\n", ifa->ifa_name);

if (getnameinfo (ifa->ifa_addr, salen,
ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) < 0)
{
perror ("getnameinfo");
continue;
}
printf ("IP : %s\n", ip);

if (getnameinfo (ifa->ifa_netmask, salen,
ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) < 0)
{
perror ("getnameinfo");
continue;
}
printf ("Netmask : %s\n", ip);

if (getnameinfo (ifa->ifa_broadaddr, salen,
ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) < 0)
{
perror ("getnameinfo");
continue;
}
printf ("Broadcast : %s\n", ip);

}

freeifaddrs (ifp);

return 0;
}

int main(int argc, char **argv)
{
printLocalIps();
}






Result :

<---------->
lo :
IP : 127.0.0.1
Netmask : 255.0.0.0
Broadcast : 127.0.0.1
<---------->
eth0 :
IP : 192.168.168.67
Netmask : 255.255.255.0
Broadcast : 192.168.168.255











沒有留言:

張貼留言