-
#include <stdio.h>
-
#include <unistd.h>
-
#include <string.h>
-
#include <sys/types.h>
-
#include <sys/socket.h>
-
#include <sys/ioctl.h>
-
#include <netinet/in.h>
-
#include <net/if.h>
-
#include <arpa/inet.h>
-
-
//convert ip address string into uint
-
uint32_t ip2uint(const char *ip) {
-
int a, b, c, d;
-
uint32_t addr = 0;
-
-
if (sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d) != 4)
-
return 0;
-
-
addr = a << 24;
-
addr |= b << 16;
-
addr |= c << 8;
-
addr |= d;
-
return addr;
-
}
-
-
//read ip address
-
char * getipaddress(char * interface)
-
{
-
int fd;
-
struct ifreq ifr;
-
-
fd = socket(AF_INET, SOCK_DGRAM, 0);
-
ifr.ifr_addr.sa_family = AF_INET; //I want to get an IPv4 IP address
-
strncpy(ifr.ifr_name, interface, IFNAMSIZ - 1); //I want IP address attached to "enp13s0"
-
ioctl(fd, SIOCGIFADDR, &ifr);
-
close(fd);
-
return inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
-
}
-
-
int main()
-
{
-
/* display result */
-
printf("%s\n", getipaddress("enp13s0"));
-
printf("%u\n", ip2uint(getipaddress("enp13s0")));
-
return 0;
-
}
[root@localhost 桌面]# gcc tmp.c -o tmp
[root@localhost 桌面]# ./tmp
10.108.162.227
174891747
[root@localhost 桌面]#
阅读(1119) | 评论(0) | 转发(0) |