#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <net/if_arp.h>
#include <net/if.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char ipbuf[16];
getlocaip(ipbuf);
printf("loca ip = %s/n", ipbuf);
exit(0);
}
int getlocaip(char *ip)
{
int sockfd;
if(-1 == (sockfd = socket(PF_INET, SOCK_STREAM, 0)))
{
perror( "socket" );
return -1;
}
struct ifreq req;
struct sockaddr_in *host;
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 1;
}
linux 下获取本地IP地址
最新推荐文章于 2026-06-17 22:56:21 发布
本文介绍了一个简单的C语言程序,该程序通过系统调用获取并打印指定网卡(如eth0)的IPv4地址。涉及的主要步骤包括创建套接字、使用ioctl进行系统调用以获取接口地址信息,并将得到的地址转换为点分十进制形式。

296

被折叠的 条评论
为什么被折叠?



