本文共 939 字,大约阅读时间需要 3 分钟。
找了许久,找到了三个函数跟这个功能有关的。分别介绍一下把。
unsigned long inet_addr( __in const char *cp);是把char *型的字符串数组的指针。
如char a[] = "192.168.2.1" a为指针。转化为unsigned long型的。这个用处不大。
以下两个是主要的:
1)首先添加头文件#include <arpa/inet.h>
2)函数1:int inet_aton(const char * cp,struct in_addr *inp)
其中struct in_addr的结构体声明如下
struct in_addr{
unsigned long int s_addr;
}
这个函数是把字符串如"192.168.1.1"转化成这个结构体。
返回值的话 参看man吧。输入命令man inet_aton查看吧。
函数2:char *inet_ntoa(struct in_addr * inp)
把struct in_addr转化成char 数组。
举个栗子:
点分式char型数组转向unsigned int
struct in_addr _inaddrs,_inaddrd;
struct tuple4 *ip_address;
ip_address = (struct tuple4 *)malloc(sizeof(struct tuple4 *));
memset(ip_address,0,sizeof(struct tuple4 *));
inet_aton("192.168.0.2", &_inaddrs);
ip_address->saddr = (unsigned int)_inaddrs.s_addr;
ip_address->saddr是u-int型的
转回来:unsigned int 转向点分式char型数组
struct in_addr _inaddrs,_inaddrd;
_inaddrs.s_addr = ip_address->saddr;
strcpy(a , inet_ntoa(_inaddrs));
总结 多利用msdn和man工具查询函数。多写一些函数、
转载地址:http://ptbci.baihongyu.com/