#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ETH_NAME "eth1" /*这个是网卡的标识符*/
int main()
{
int sock;
struct sockaddr_in sin;
struct ifreq ifr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
{
perror("socket");
return -1;
}
strncpy(ifr.ifr_name, ETH_NAME, IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
{
perror("ioctl");
return -1;
}
memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
fprintf(stdout, "eth0: %s/n", inet_ntoa(sin.sin_addr));
return 0;
}
运行过程中有可能会报错:
ioctl: Cannot assign requested address
或者no device
说明网卡的标识符不对,找出网卡的标识符比如为eth2,改eth1为eth2即可
本文介绍了一个C程序,用于获取指定网卡(如eth1)的IP地址。如果运行时出现'Cannot assign requested address'错误,说明网卡标识符不正确。解决方案是确定正确的网卡标识符(如eth2),并将代码中的eth1替换为eth2。
1034

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



