#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const char* const ETH = "eth0";
int GetIP2(string &ip)
{
int socket_fd;
struct sockaddr_in *sin;
struct ifreq ifr;
struct ifconf;
socket_fd = socket(AF_INET,SOCK_DGRAM,0);
if(socket_fd ==-1)
{
perror("socket error!\n");
return -1;
}
strcpy(ifr.ifr_name,ETH);
//这里要特别的注意,根据自己的系统的不同会有所差异有可能会是“eth0“。 如果出现错误提示 No such device 可能是这里的问题
if(ioctl(socket_fd,SIOCGIFADDR,&ifr) < 0)
{
perror("ioctl error\n");
close(socket_fd);
return -1;
}
else
{
sin = (struct sockaddr_in *)&(ifr.ifr_addr);
ip = inet_ntoa(sin->sin_addr);
}
close(socket_fd);
return 0;
}
int main()
{
string ip;
string os;
#ifdef WIN32
os = "WIN7";
#else
os = "CentOs";
#endif
GetIP2(ip);
printf("current ip is : %s\n", ip.c_str());
printf("current os is : %s\n", os.c_str());
return 0;
}