#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int inet_sock;
struct ifreq ifr;
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
char current_osd_ip[20];
strcpy(ifr.ifr_name, "eth1");
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0){
perror("ioctl");
strcpy(ifr.ifr_name, "eth0");
if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0){
perror("ioctl");
goto ip_error;
}
}
strcpy(current_osd_ip, inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
printf("\nValid IP address of this machine is: %s\n", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
return 0;
ip_error:
printf("\nNO valid ip address on this machine...\n");
return 0;
}
获取本机ip地址
最新推荐文章于 2020-06-01 17:19:58 发布