ipaddress和字符串之间的转化
(2011-11-08 15:22:38)
标签:
杂谈 |
分类: Linux |
今天遇到了需要将in_addr结构的ipaddress转化成字符串模式,在网上搜索了一下实现的方法,总结一下。
http://www.retran.com/beej/inet_ntoaman.html
用以上三个函数可以实现。
inet_ntoa()可以将in_addr类型的ipaddress转化成字符串,返回一个char型的指针;
它的返回值是一个由inet_ntoa()控制的静态的固定的指针,所以每次调用 inet_ntoa(),它就将覆盖上次调用时所得的IP地址,所以,如果需要多次调用,需把之前的内容储存。
inet_aton()可以将字符串(特别是255.255.255.255)转化成in_addr类型的ipaddress;
inet_addr()是一个老函数了,和inet_aton()功能一样,不过不能转化255.255.255.255认为这个ip值是无效的。
函数原型:
Prototypes
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
// ALL THESE ARE DEPRECATED! Use inet_pton() or inet_ntop() instead!!
char *inet_ntoa(struct in_addr in);
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
Example
struct sockaddr_in antelope;
char *some_addr;
inet_aton("10.0.0.1", &antelope.sin_addr); // store IP in antelope
some_addr = inet_ntoa(antelope.sin_addr); // return the IP
printf("%s\n", some_addr); // prints "10.0.0.1" // and this call is the same as the inet_aton() call, above:
antelope.sin_addr.s_addr = inet_addr("10.0.0.1");
具体描述可以查看
后一篇:(转)sed直接替换文件内容