域名解析

#include<netinet/in.h>

struct in_addr {
	in_addr_t s_addr;	//32-bit IPv4 address,BE
};
struct sockaddr_in {
	uint8_t			sin_len;	//該結構長度 16-bit
	sa_family_t		sin_family;	//AF_INET
	in_port_t		sin_port;	//端口號
	struct in_addr	sin_addr;	//32-bit IP地址
	char			sin_zero[8];  //保留
};

  

 

經過域名獲取IP地址,IP地址兩個表達方式的轉換(點分十進制,數值格式,eg:255.255.0.0---0x0000FFFF(網絡字節序)),字節序的轉換編程

 

socket編程接口網絡

#include<netdb.h>
#include<sys/socket.h>

//經過域名獲取IP地址
struct hostent *gethostbyname(const char *name);
/*	name:域名,eg:"www.baidu.com"
*/
//經過二進制的IP地址找到對應的域名
struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type);
/*	addr:二進制ip
	len:ip長度,對於IPv4是4
	type:AF_INET
*/
struct hostent {
	char  *h_name;            /* official name of host */
	char **h_aliases;         /* alias list */
	int    h_addrtype;        /* host address type */
	int    h_length;          /* length of address */
	char **h_addr_list;       /* list of addresses */
}
/*	char* 字符串都是以 '\0' 結束的
	char** 字符串指針都是以 NULL 結束的
*/

//ip地址格式轉換
#include <arpa/inet.h>
//點分十進制轉換爲數值形式
int inet_pton(int af, const char *src, void *dst);
/*	af: AF_INET/AF_INET6,對應IPv4/IPv6
	src: 點分十進制字符串,eg: "255.255.0.0"
	dst: 存放轉換結果的,對應解析爲 0x0000FFFF,大端
	返回:成功,1;src無效,0;出錯,-1;
*/
//數值形式轉換爲點分十進制形式
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
/*	src:網絡字節序,二進制形式,eg: 0x0000ffff
	dst:存放轉換結果,點分十進制字符串
	size:指定字符串長度
	返回:成功,dst;出錯,NULL
*/

//主機字節序和網絡字節序轉換
#include <arpa/inet.h>

uint32_t htonl(uint32_t hostlong);

uint16_t htons(uint16_t hostshort);

uint32_t ntohl(uint32_t netlong);

uint16_t ntohs(uint16_t netshort);

  

使用例子socket

#include<stdio.h>
#include<stdlib.h>
#include<netdb.h>
#include<arpa/inet.h>
void printHostent(struct hostent *p)
{
	printf("%s\n",p->h_name);
	char **q=p->h_aliases;
	while(*q!=NULL){
		printf("%s\n",*q);
		++q;
	}
	printf("%d %d\n",p->h_addrtype,p->h_length);
	q=p->h_addr_list;
	char str[16];
	while(*q!=NULL){
		printf("%s\n",inet_ntop(AF_INET,*q,str,16));
		//printf("%s\n",str);
		++q;
	}	
}
int main()
{
	printf("struct hostent of www.baidu.com:\n");
	char *host="www.baidu.com";
	struct hostent *p=gethostbyname(host);
	if(p==NULL)
		printf("gethostbyname failed\n");
	else
		printHostent(p);
	
	printf("\npresentation ip---numeric ip\n");
	unsigned int a;
	inet_pton(AF_INET,"255.255.0.0",&a);
	printf("numeric ip network byte order: %x\n",a);
	printf("host byte order: %x\n",ntohl(a));
	char str[16];
	inet_ntop(AF_INET,&a,str,16);
	printf("presentation ip: %s\n",str);
}
相關文章
相關標籤/搜索