获取本机ip(成功版)

参照网上用ioctl的SIOCGIFCONF方法获取本地ip成功,代码如下:

#include <stdio.h>
#include <stdlib.h>           /* for exit() */
#include <string.h>            
#include <sys/socket.h>       /* for socket() */
#include <sys/types.h>        /* for socket() */
#include <net/if.h>           /* for struct ifreq */
#include <linux/sockios.h>    /* for SIOCGIFADDR */
#include <netinet/in.h>       /* for struct sockaddr_in */
#include <arpa/inet.h>        /* for inet_ntoa() */

int main(int argc, char *argv[])
{
	char ipbuf[16];
	getlocaip(ipbuf);
	printf("local ip is: %s\n", ipbuf);
	exit(0);
}

int getlocaip(char *ip)
{
	int sockfd;
	struct ifreq req;
	struct sockaddr_in *host;

	if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
	{
		perror("socket");
		return -1;
	}

	bzero(&req, sizeof(struct ifreq));
	strcpy(req.ifr_name, "eth0");
	ioctl(sockfd, SIOCGIFADDR, &req);
	host = (struct sockaddr_in*)&req.ifr_addr;
	strcpy(ip, inet_ntoa(host->sin_addr));

	close(sockfd);
	return 0;
}

因为头文件是后来一个个的加上去的,所以在尝试的过程中,编译的时候出现很多错误,虽然都是比较常见的,也记录一下:


1.出现警告:

警告: 传递‘strcpy’的第 2 个参数时将整数赋给指针,未作类型转换

 原因:没有把inet_ntoa()函数的头文件加上

 解决方法:加上头文件 #include <arpa/inet.h>


2.出现错误:

错误: 提领指向不完全类型的指针

原因:这种错误主要是因为使用的结构体定义的头文件没有包含进来,我这主要是忘了把定义struct sockaddr_in的头文件

 解决方法:加上结构体对应的头文件(我的是#include <netinet/in.h>)


3.执行程序打印的ip是0.0.0.0

原因:计算机网卡eth0没有获取到ip,可以用ifconfig看下:

解决方法:用ifconfig手动设置ip后再执行程序:

 

 


搞定碎觉!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章