Chinaunix
标题:
linux C 获取IP
[打印本页]
作者:
liuhengloveyou
时间:
2010-02-25 08:59
标题:
linux C 获取IP
本帖最后由 liuhengloveyou 于 2010-02-25 09:01 编辑
#include <sys/socket.h>
#include <unistd.h>
#include <net/if.h>
#include <string.h>
#include <stdio.h>
#include <linux/sockios.h>
#include <arpa/inet.h>
#define BUFSIZE 16
/*
* 获得指定网口的IP
*/
int get_inetip(char *in_name, char *buf)
{
int socket_fd;
struct ifreq ifr;
struct ifconf conf;
if ((socket_fd = socket(AF_INET,SOCK_DGRAM,0)) == -1) {
perror("socket error!\n");
return -1;
}
strcpy(ifr.ifr_name, in_name);
if(ioctl(socket_fd,SIOCGIFADDR,&ifr) < 0) {
perror("ioctl error\n");
return -1;
}
strcpy(buf, inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr));
return 0;
}
int main(void)
{
char buff[BUFSIZE];
get_inetip("eth0", buff);
printf("%s\n", buff);
return 0;
}
复制代码
昨天要这功能, 论坛里没找到很好的实现, 就自己实现了个. 比较简单.
作者:
jjj137
时间:
2010-02-25 12:43
呵呵,每次用到时候都是去查 man ……
作者:
wesleyluo
时间:
2010-03-11 17:03
我是来学习的。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2