我有一段遗留代码,需要在大型和小型Endian机器上运行。问题在于hton()。
msg->Mac是char Mac16+1 现有代码:(只在上工作)
if (sscanf(msg->Mac, "%4hx.%4hx.%4hx", (unsigned short *)&new_mac[0],
(unsigned short *)&new_mac[2],
(unsigned short *)&new_mac[4]) != 3) {
return (ERROR_ADDRESS_TRANSLATION);
}
*(unsigned short *)&new_mac[0] = hton(*(unsigned short *)&new_mac[0]);
*(unsigned short *)&new_mac[2] = hton(*(unsigned short *)&new_mac[2]);
*(unsigned short *)&new_mac[4] = hton(*(unsigned short *)&new_mac[4]);
sprintf((char *)newMac, "%04x.%04x.%04x", *(unsigned short *)&new_mac[0],
*(unsigned short *)&new_mac[2], *(unsigned short *)&new_mac[4]);
/* Get the MAC address */
if (sscanf((char *)newMac, "%4hx.%4hx.%4hx", (unsigned short *)&mac_addr[0],
(unsigned short *)&mac_addr[2],
(unsigned short *)&mac_addr[4]) != 3) {
return (ERROR_ADDRESS_TRANSLATION);
}
/* Convert to network order */
*(unsigned short *)&mac_addr[0] = hton(*(unsigned short *)&mac_addr[0]);
*(unsigned short *)&mac_addr[2] = hton(*(unsigned short *)&mac_addr[2]);
*(unsigned short *)&mac_addr[4] = hton(*(unsigned short *)&mac_addr[4]);为了在小终端机器上修复这个问题,我使用了一个交换宏,它将在短时间内交换字节。这样做对吗?
我在上面添加的代码:(为了使它在很少的情况下也能工作)
#if __BYTE_ORDER != __BIG_ENDIAN
*(unsigned short *)&mac_addr[0] = SWAP(*(unsigned short *)&mac_addr[0]);
*(unsigned short *)&mac_addr[2] = SWAP(*(unsigned short *)&mac_addr[2]);
*(unsigned short *)&mac_addr[4] = SWAP(*(unsigned short *)&mac_addr[4]);
#endif发布于 2015-07-30 12:28:32
你在小安迪安机器上测试过吗?既然赫顿已经考虑到了拱门的位置:
/* Copyright (C) 1993-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <stdint.h>
#include <netinet/in.h>
#undef htonl
#undef ntohl
uint32_t
htonl (uint32_t x)
{
#if BYTE_ORDER == BIG_ENDIAN
return x;
#elif BYTE_ORDER == LITTLE_ENDIAN
return __bswap_32 (x);
#else
# error "What kind of system is this?"
#endif
}
weak_alias (htonl, ntohl)发布于 2015-07-30 12:34:43
特别是对于MAC地址:它们应该被看作是一个6个字节的数组,所以不应该出现不可移植的问题。试图映射其他类型(为了效率?)只是自找麻烦。
因此,扫描应是:
sscanf(msg->Mac, "%2hhx%2hhx.%2hhx%2hhx.%2hhx%2hhx",
&new_mac[0], &new_mac[1],
&new_mac[2], &new_mac[3],
&new_mac[4], &new_mac[5])https://stackoverflow.com/questions/31723227
复制相似问题