当前位置:编程学习 > 网站相关 >>

inet_ntoa在64位机器上出错

inet_ntoa用法如下:

[html] 
char *inet_ntoa(struct in_addr in); 
就是将struct in_addr结构转换为IP地址的形式,struct in_addr这个结构应该不陌生吧,它的定义如下:

[cpp] 
struct in_addr{ 
       unsigned long s_addr; 

struct sockaddr_in { 
       short int sin_family; 
       unsigned short int sin_port;  
       struct in_addr sin_addr; 
       unsigned char sin_zero[8]; 
}; 
在服务器端使用accept函数之后,会得到客户端连接的struct sockaddr结构,然后将其转换成struct sockaddr_in结构,此时可以在服务器端得到客户端连接的IP和端口数据。

这时用这个函数有一个问题是:如果在64位的机器上,使用

[cpp] 
char* tmp = inet_ntoa(sin->sin_addr); 
之后,对tmp进行操作,会出现断错误,但在32位机器上没有问题,原因是64位时inet_ntoa返回值是一个整型。
在网上找的两种解决办法:

在使用的文件中,引用#include <arpa/inet.h>头文件。
直接使用inet_ntop函数。
inet_ntop的说明如下:

[html]
NAME 
       inet_ntop - Parse network address structures 
 
SYNOPSIS 
       #include <sys/types.h> 
       #include <sys/socket.h> 
       #include <arpa/inet.h> 
 
       const char *inet_ntop(int af, const void *src, 
                             char *dst, socklen_t cnt); 
 
DESCRIPTION 
       This  function converts the network address structure src in the af address family into a char- 
       acter string, which is copied to a character buffer dst, which is cnt bytes long. 
 
       inet_ntop(3)  extends  the  inet_ntoa(3)  function  to  support  multiple   address   families, 
       inet_ntoa(3)  is  now  considered  to  be  deprecated  in favor of inet_ntop(3).  The following 
       address families are currently supported: 
 
       AF_INET 
              src points to a struct in_addr (network byte order format) which is converted to an IPv4 
              network address in the dotted-quad format, "ddd.ddd.ddd.ddd".  The buffer dst must be at 
              least INET_ADDRSTRLEN bytes long. 
 
       AF_INET6 
              src points to a struct in6_addr (network byte order format) which is converted to a rep- 
              resentation of this address in the most appropriate IPv6 network address format for this 
              address.  The buffer dst must be at least INET6_ADDRSTRLEN bytes long. 
 
RETURN VALUE 
       inet_ntop() returns a non-null pointer to dst.  NULL is returned if there was  an  error,  with 
       errno set to EAFNOSUPPORT if af was not set to a valid address family, or to ENOSPC if the con- 
       verted address string would exceed the size of dst given by the cnt argument. 
 
CONFORMING TO 
       POSIX.1-2001.  Note that RFC 2553 defines a prototype where the last parameter cnt is  of  type 
       size_t.  Many systems follow RFC 2553.  Glibc 2.0 and 2.1 have size_t, but 2.2 has socklen_t. 

 

补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,