获取服务器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/archive/2011/07/04/2097363.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值