获取服务器ip地址

#include <stdio.h>
#include
<sys/types.h>
#include
<sys/socket.h>
#include
<sys/ioctl.h>
#include
<netinet/in.h>
#include
<net/if.h>
#include
<net/if_arp.h>
#include
<arpa/inet.h>
#include
<errno.h>
#include
<string.h>
#define ETH_NAME "eth1"

int main()
{
int sock;
struct sockaddr_in sin;
struct ifreq ifr;

sock
= socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
{
perror(
"socket");
return -1;
}

strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ
- 1] = 0;

if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
{
perror(
"ioctl");
return -1;
}

memcpy(
&sin, &ifr.ifr_addr, sizeof(sin));
fprintf(stdout,
"eth0: %s\n", inet_ntoa(sin.sin_addr));

return 0;
}
上述代码有个毛病,只能获取一张网卡的ip地址。哎呀哎呀,真的很难得获得所有网卡的ip地址
不知道怎么获取。
下述代码就无敌了。什么都可以获取。
#include<stdio.h>
#include
<unistd.h>
#include
<iostream>
using namespace std;
int main()
{
FILE
*fp = popen("/sbin/ifconfig -a | grep -v inet6 | awk '/inet/{print $2}' | awk -F: '{print $2}'","r");
char str[1024];
fread(str,
sizeof(str),1,fp);
cout
<<str;
pclose(fp);
}
~
原文地址:https://www.cnblogs.com/xloogson/p/2097363.html