#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* 字符串都是以 ' ' 结束的 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);
使用例子
#include<stdio.h> #include<stdlib.h> #include<netdb.h> #include<arpa/inet.h> void printHostent(struct hostent *p) { printf("%s ",p->h_name); char **q=p->h_aliases; while(*q!=NULL){ printf("%s ",*q); ++q; } printf("%d %d ",p->h_addrtype,p->h_length); q=p->h_addr_list; char str[16]; while(*q!=NULL){ printf("%s ",inet_ntop(AF_INET,*q,str,16)); //printf("%s ",str); ++q; } } int main() { printf("struct hostent of www.baidu.com: "); char *host="www.baidu.com"; struct hostent *p=gethostbyname(host); if(p==NULL) printf("gethostbyname failed "); else printHostent(p); printf(" presentation ip---numeric ip "); unsigned int a; inet_pton(AF_INET,"255.255.0.0",&a); printf("numeric ip network byte order: %x ",a); printf("host byte order: %x ",ntohl(a)); char str[16]; inet_ntop(AF_INET,&a,str,16); printf("presentation ip: %s ",str); }