修改#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <arpa/inet.h> int main() { int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); ifr.ifr_addr.sa_family = AF_INET; //strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); strncpy(ifr.ifr_name, "enp3s0", IFNAMSIZ-1); ioctl(fd, SIOCGIFHWADDR, &ifr); close(fd); unsigned char *mac = (unsigned char *) ifr.ifr_hwaddr.sa_data; printf("MAC Address: %02X:%02X:%02X:%02X:%02X:%02X\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return 0; }获取IP地址
时间: 2024-03-12 09:43:47 浏览: 80
你可以使用SIOCGIFADDR命令来获取网络接口的IP地址,需要将ifr.ifr_addr.sa_family设置为AF_INET,然后调用ioctl函数来获取IP地址。下面是一个示例代码:
```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
int main() {
int fd;
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
//strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
strncpy(ifr.ifr_name, "enp3s0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr;
char* ip = inet_ntoa(addr->sin_addr);
printf("IP Address: %s\n", ip);
return 0;
}
```
其中,inet_ntoa函数用于将网络字节序的IP地址转换为字符串格式。
阅读全文