[英]how to convert IP address in char[] to Uint32_t in c?
我写了一个以IP地址为参数的程序,我想将此IP地址存储在unit32_t中。 我可以轻松地将uint32_t转换回字符数组。 如何将字符数组中的IP地址转换为uint32_t。
例如
./IPtoCHAR 1079733050
uint32_t到IP地址=> 64.91.107.58
但是,如何编写执行反向任务的程序?
./CHARtoIP 64.91.107.58
对于第一个IPtoCHAR,它是
unsigned int ipAddress = atoi(argv [1]);
printf(“ IP地址%d。%d。%d。%d \\ n”,((ipAddress >> 24)&0xFF),((ipaddress >> 16)&0xFF),((ipaddress >> 8)& 0xFF),(ipAddress&0xFF));
但是下面所有这些都不起作用
uint32_t aa =(uint32_t)(“ 64.91.107.58”);
uint32_t aa = atoi(“ 64.91.107.58”);
uint32_t aa = strtol(“ 64.91.107.58”,NULL,10);
如果您由于其他任何奇怪的原因而无法访问inet_ *函数或需要自己编写此代码,则可以使用以下函数:
#include <stdio.h>
/**
* Convert human readable IPv4 address to UINT32
* @param pDottedQuad Input C string e.g. "192.168.0.1"
* @param pIpAddr Output IP address as UINT32
* return 1 on success, else 0
*/
int ipStringToNumber (const char* pDottedQuad,
unsigned int * pIpAddr)
{
unsigned int byte3;
unsigned int byte2;
unsigned int byte1;
unsigned int byte0;
char dummyString[2];
/* The dummy string with specifier %1s searches for a non-whitespace char
* after the last number. If it is found, the result of sscanf will be 5
* instead of 4, indicating an erroneous format of the ip-address.
*/
if (sscanf (pDottedQuad, "%u.%u.%u.%u%1s",
&byte3, &byte2, &byte1, &byte0, dummyString) == 4)
{
if ( (byte3 < 256)
&& (byte2 < 256)
&& (byte1 < 256)
&& (byte0 < 256)
)
{
*pIpAddr = (byte3 << 24)
+ (byte2 << 16)
+ (byte1 << 8)
+ byte0;
return 1;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.