IP地址转换函数——inet_ntop(),inet_pton(),htonl(),ntohl()

1、点分十进制字符串(dotted-decimal notation)与二进制数值互转

const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
int inet_pton(int af, const char *src, void *dst);
注意:

(1) 二进制数值形式是网络字节序(network byte order),即大端,所以,如果所给地址是主机字节序(host byte order)(Intel CPU 是小端),则调用这 inet_ntop() 时,先转为网络字节序

(2) inet 指 IPv4 , n 指 network byte order


2、网络字节序与主机字节序互转

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

我自己写一个主机字节序地址直接转为点分十进制字符串的程序:

/*
convert IPv4 addresses from binary form to text string form
*/
#include 
#include 
#include 

const char *ipv4_btostr(uint32_t ip_bin, char *ip_str, size_t size);

int main()
{
	uint32_t ip_bin;	// ip address in binary form
	char ip_str[16];	// ip address in dotted-decimal string

	ip_bin = 0xbff0001;	// 11.255.0.1
	ipv4_btostr(ip_bin, ip_str, 16);
	printf("%s\n", ip_str);

	return 0;
}

const char *ipv4_btostr(uint32_t ip_bin, char *ip_str, size_t size)
{
	if(size < 16)
	{
		return NULL;
	}
	char *ip_bin_p = NULL;	// point to ip_bin
	char tempstr[4];
	char *p = NULL;
	int i;
	int len;

	ip_bin_p = (char *)(&ip_bin);
	ip_bin_p += 3;
	p = ip_str;
	for(i = 0; i < 4; i++)
	{
		sprintf(tempstr, "%d", (int)(unsigned char)(*ip_bin_p));	// convert every byte to string
																	// don't omit unsigned char, think why?
		strcpy(p, tempstr);
		if(i != 3)
		{
			p += strlen(tempstr);
			*p = '.';
			p++;
			ip_bin_p--;
		}
	}
	return ip_str;
}





你可能感兴趣的:(网络编程,Linux,Programming)