网络编程 UDP 主机网络信息取得
1,if_nametoindex 通过网卡名字取得网卡编号
2,if_indextoname 通过网卡编号取得网卡名字
#include <stdio.h>
#include <string.h>
#include <net/if.h>
int main(){
int index;
char buf[128];
//根据名字取得编号
index = if_nametoindex("enp0s3");
if(index == 0){
perror("if_nametoindex");
return 1;
}
printf("index:%d\n", index);
memset(buf, 0, sizeof(buf));
//根据编号取得名字
if(if_indextoname(index, buf) == NULL){
perror("if_indextoname");
return 1;
}
printf("name:%s\n", buf);
return 0;
}
github源代码
3,getifaddrs 取得网卡的名字,取得网卡的flags,取得IP地址,取得netmask
#include <stdio.h>
#include <string.h>
#include <ifaddrs.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(){
ifaddrs *ifa_list;
ifaddrs *ifa;
int n;
char addrstr[256], netmaskstr[256];
n = getifaddrs(&ifa_list);
if(n != 0){
return 1;
}
for(ifa = ifa_list; ifa != NULL; ifa = ifa->ifa_next){
printf("ifa_name:%s\n", ifa->ifa_name);
printf("ifa_flags: 0x%.8x\n", ifa->ifa_flags);
memset(addrstr, 0, sizeof(addrstr));
memset(netmaskstr, 0, sizeof(netmaskstr));
//IPv4
if(ifa->ifa_addr->sa_family == AF_INET){
//IP
inet_ntop(AF_INET,
&((sockaddr_in*)ifa->ifa_addr)->sin_addr,
addrstr, sizeof(addrstr));
//mask
inet_ntop(AF_INET,
&((sockaddr_in*)ifa->ifa_netmask)->sin_addr,
netmaskstr, sizeof(netmaskstr));
printf(" IPv4: %s netmask : %s\n", addrstr, netmaskstr);
}
//IPv6
else if(ifa->ifa_addr->sa_family == AF_INET6){
//IP
inet_ntop(AF_INET6,
&((sockaddr_in6*)ifa->ifa_addr)->sin6_addr,
addrstr, sizeof(addrstr));
//mask
inet_ntop(AF_INET6,
&((sockaddr_in6*)ifa->ifa_netmask)->sin6_addr,
netmaskstr, sizeof(netmaskstr));
printf(" IPv6: %s netmask : %s\n", addrstr, netmaskstr);
}
else if(ifa->ifa_addr->sa_family == AF_PACKET){
printf(" af_packet:%d\n", ifa->ifa_addr->sa_family);
}
else{
printf(" else:%d\n", ifa->ifa_addr->sa_family);
}
printf("\n");
}
freeifaddrs(ifa_list);
return 0;
}
github源代码
c/c++ 学习互助QQ群:877684253
本人微信:xiaoshitou5854