怎么用C语言获取Linux系统的网卡IP地址

怎么用C语言获取Linux系统的网卡IP地址,第1张

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <net/if.h>

#include <netdb.h>

#include <arpa/inet.h>

#include <sys/ioctl.h>

//获取地址

//返回IP地址字符串

int getlocalip(char* outip)

{

int i=0

int sockfd

struct ifconf ifconf

char buf = (char)malloc(512)

struct ifreq *ifreq

char* ip

//初始化ifconf

ifconf.ifc_len = 512

ifconf.ifc_buf = buf

if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0)

{

return -1

}

ioctl(sockfd, SIOCGIFCONF, &ifconf) //获取所有接口信息

close(sockfd)

//接下来一个一个的获取IP地址

ifreq = (struct ifreq*)buf

i = ifconf.ifc_len/sizeof(struct ifreq)

char *pos = outip

int count

for(count = 0 (count < 5 && i > 0) i--)

{

ip = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr)

if(strncmp(ip,"127.0.0.1", 3)==0) //排除127.x.x.x,继续下一个

{

ifreq++

continue

}else

{

printf("%s\n", ip)

strcpy(pos,ip)

int len = strlen(ip)

pos = '\t'

pos += len+1

count ++

ifreq++

}

}

free(buf)

return 0

}

//——————————-函数的调用方式————————————-

int main(int argc, char** argv)

{

char ip = {'*'}

if ( getlocalip( ip ) == 0 )

{

printf("本机IP地址是: %s\n", ip )

}

else

{

printf("无法获取本机IP地址 ")

}

return 0

}

有的fd为你连接设备的网络套接字。

你直接输入套接字就可以得到了连接设备ip和端口了。

struct sockaddr_in sa

int len1 = sizeof(sa)

if(getpeername(fd, (struct sockaddr *)&sa, &len1))

{

fprintf(stderr,"get client ip and port failed,exit!\n")

}

printf("ip=%s|端口=%s\n",inet_ntoa(sa.sin_addr),ntohs(sa.sin_port))ip|port

方案一:

你用C语言去读取/etc/resolv.conf,格式是namserver *.*.*.* 提取以下 就有DNS了

至于网关 你可以去读取/etc/sysconfig/network /etc/sysconfig/network-scripts/ifcfg-eth0等文件,但是各个Linux系统可能少有差别。

方案二:

在C程序中调用exec函数,执行route命令,从返回的结果中提取网关

至于DNS 也可以通过dig localhost, 从结果中提取DNS 但是就没有方案一中快了


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/8920305.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-23
下一篇2023-04-23

发表评论

登录后才能评论

评论列表(0条)

    保存