1. 程式人生 > >C語言 獲取本機IP地址,非迴環地址

C語言 獲取本機IP地址,非迴環地址

#include   <stdio.h>   
#include   <sys/types.h>   
#include   <sys/socket.h>   
#include   <sys/ioctl.h>   
#include   <netinet/in.h>   
#include   <net/if.h>   
#include   <net/if_arp.h>   
#include   <arpa/inet.h>   
#include   <errno.h>   

#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即可