1. 程式人生 > >unix網路程式設計之根據主機名(hostname)或網絡卡名獲取IP地址(三種方法)

unix網路程式設計之根據主機名(hostname)或網絡卡名獲取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>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>

//使用getaddrinfo函式,根據hostname獲取IP地址
int getIpAddrByHostname_1(char *hostname, char *ip_str, size_t ip_size)
{
	struct addrinfo *result = NULL, hints;
	int ret = -1;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_DGRAM;
	ret = getaddrinfo(hostname, NULL, &hints, &result);

	if (ret == 0)
	{
		struct in_addr addr = ((struct sockaddr_in *)result->ai_addr)->sin_addr;
		const char *re_ntop = inet_ntop(AF_INET, &addr, ip_str, ip_size);
		if (re_ntop == NULL) 
			ret = -1;	
	}

	freeaddrinfo(result);
	return ret;
}

//使用ping指令,根據hostname獲取ip地址
int getIpAddrByHostname_2(char *hostname, char* ip_addr, size_t ip_size)
{
	char command[256];
	FILE *f;
	char *ip_pos;

	snprintf(command, 256, "ping -c1 %s | head -n 1 | sed 's/^[^(]*(\\([^)]*\\).*$/\\1/'", hostname);
	fprintf(stdout, "%s\n", command);
	if ((f = popen(command, "r")) == NULL)
	{
		fprintf(stderr, "could not open the command, \"%s\", %s\n", command, strerror(errno));
		return -1;
	}

	fgets(ip_addr, ip_size, f);
	fclose(f);

	ip_pos = ip_addr;
	for (;*ip_pos && *ip_pos!= '\n'; ip_pos++);
	*ip_pos = 0;

	return 0;
}

//使用ioctl,根據網絡卡名獲取IP地址
int getIpAddrByEthName(char *eth_name, char* ip_addr, size_t ip_size)
{
	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));
	strcpy(ip_addr, inet_ntoa(sin.sin_addr));	
	
	return 0;
}

int main()
{
	char addr[64] = {0};
	getIpAddrByHostname_1("localhost", addr, INET_ADDRSTRLEN);
	fprintf(stdout, "localhost: %s\n", addr);
	
	getIpAddrByHostname_2("localhost", addr, INET_ADDRSTRLEN);
	fprintf(stdout, "localhost: %s\n", addr);
	
	getIpAddrByEthName("eth0", addr, INET_ADDRSTRLEN);
	fprintf(stdout, "eth0: %s\n", addr);
	
	return 0;
}