您的位置:首页 > 理论基础 > 计算机网络

UNIX网络编程学习(5)--只支持IPv4的inet_pton和inet_ntop的简化版本

2012-03-22 21:03 288 查看
inet_pton:

#include	<sys/types.h>
#include	<sys/socket.h>
#include	<netinet/in.h>
#include	<arpa/inet.h>
#include	<errno.h>
#include	<string.h>

/* Delete following line if your system's headers already DefinE this
function prototype */
int		 inet_aton(const char *, struct in_addr *);

/* include inet_pton */
int
inet_pton(int family, const char *strptr, void *addrptr)
{
if (family == AF_INET) {
struct in_addr  in_val;

if (inet_aton(strptr, &in_val)) {
memcpy(addrptr, &in_val, sizeof(struct in_addr));
return (1);
}
return(0);
}
errno = EAFNOSUPPORT;
return (-1);
}
/* end inet_pton */

 

inet_ntop:

#include	<sys/types.h>
#include	<sys/socket.h>
#include	<errno.h>
#include	<stdio.h>

#ifndef	INET_ADDRSTRLEN
#define	INET_ADDRSTRLEN		16
#endif

/* include inet_ntop */
const char *
inet_ntop(int family, const void *addrptr, char *strptr, size_t len)
{
const u_char *p = (const u_char *) addrptr;

if (family == AF_INET) {
char	temp[INET_ADDRSTRLEN];

snprintf(temp, sizeof(temp), "%d.%d.%d.%d",
p[0], p[1], p[2], p[3]);
if (strlen(temp) >= len) {
errno = ENOSPC;
return (NULL);
}
strcpy(strptr, temp);
return (strptr);
}
errno = EAFNOSUPPORT;
return (NULL);
}
/* end inet_ntop */


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息