linux獲取本機網絡卡ip位址

2021-06-05 13:37:18 字數 1784 閱讀 5084

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#include ;

#define eth_name "eth0"

int main()

strncpy(ifr.ifr_name, eth_name, ifnamsiz);

ifr.ifr_name[ifnamsiz - 1] = 0;

if (ioctl(sock, siocgifaddr, &ifr) < 0)

memcpy(&sin, &ifr.ifr_addr, sizeof(sin));

fprintf(stdout, "eth0: %s\n", inet_ntoa(sin.sin_addr));

return 0;

上面的**需要在巨集裡指定要獲取的網絡卡名。

下面的**可以獲取到所有的網絡卡資訊。

#include #include #include #include #include #include #include #include #ifdef solaris 

#include #endif

#define maxinte***ces 16

main (argc, argv)

register int argc;

register char *argv;

} else

//判斷網絡卡狀態

if (buf[int***ce].ifr_flags & iff_up)

else

//獲取當前網絡卡的ip位址

if (!(ioctl (fd, siocgifaddr, (char *) &buf[int***ce])))

else

/* this section can't get hardware address,i don't know whether the reason is module driver*/

#ifdef solaris

//獲取mac位址

arp.arp_pa.sa_family = af_inet;

arp.arp_ha.sa_family = af_inet;

((struct sockaddr_in*)&arp.arp_pa)->sin_addr.s_addr=((struct sockaddr_in*)(&buf[int***ce].ifr_addr))->sin_addr.s_addr;

if (!(ioctl (fd, siocgarp, (char *) &arp)))

#else

#if 0

/*get hw address of the net card */

if (!(ioctl (fd, siocgenaddr, (char *) &buf[int***ce])))

#endif

if (!(ioctl (fd, siocgifhwaddr, (char *) &buf[int***ce])))

#endif

else

} //while

} else

perror ("cpm: ioctl");

} else

perror ("cpm: socket");

close (fd);

return retn;

}

Linux 獲取本機IP位址

linux 獲取本機ip位址 說明 family at inet ipv4 family at inet6 ipv6 address 提取得到的ip位址所要儲存的位址 size strlen sampleip 192.168.123.128 max ipv4 15 某些標頭檔案應在其他方面,在本程式...

獲取本機IP位址

cstring strlocalip char szhostname 64 memset szhostname,0x00,sizeof szhostname gethostname szhostname,sizeof szhostname phostent phost gethostbyname s...

獲取本機IP位址

第一步 載入winsock2靜態鏈結庫檔案。include pragma comment lib,ws2 32.lib bool loadwinsock 第二步 獲取本地的主機名稱。hostent phostent null char szhostname 256 memset szhostname...