Joy*_*Joy 4 c linux network-programming
我使用inet_pton来验证输入IP地址是否有效并且不是全零(0.0.0.0或00.00.0.0).
inet_pton(int af, const char *src, void *dst)
Run Code Online (Sandbox Code Playgroud)
如果输入ip(src)地址是0.0.0.0 inet_pton,则将dst设置为值0.如果src值为00.00.00.00,则dst值不为0,但我得到每个跟踪的随机值.为什么inet_pton将0.00.00.00转换为值0
#include <string.h>
#include <arpa/inet.h>
void main( int argc, char *argv[])
{
int s;
struct in_addr ipvalue;
printf("converting %s to network address \n", argv[1]);
s = inet_pton(AF_INET, argv[1], &ipvalue);
if(s < 0)
printf("inet_pton conversion error \n");
printf("converted value = %x \n", ipvalue.s_addr);
}
Run Code Online (Sandbox Code Playgroud)
样本运行
正确的价值观:
./a.out 10.1.2.3
converting 10.1.2.3 to network address
converted value = 302010a
Run Code Online (Sandbox Code Playgroud)
./a.out 0.0.0.0
converting 0.0.0.0 to network address
converted value = 0
Run Code Online (Sandbox Code Playgroud)
结果不正确:
./a.out 00.00.00.0
converting 00.00.00.0 to network address
converted value = **a58396a0**
Run Code Online (Sandbox Code Playgroud)
./a.out 00.0.0.0
converting 00.0.0.0 to network address
converted value = **919e2c30**
Run Code Online (Sandbox Code Playgroud)
您没有检查是否inet_pton()返回0. inet_pton的手册页指出:
inet_pton()成功返回1(网络地址已成功转换).如果src不包含表示指定地址系列中的有效网络地址的字符串,则返回0.如果af不包含有效的地址族,则返回-1并将errno设置为EAFNOSUPPORT
尝试类似的东西:
#include <stdio.h>
#include <arpa/inet.h>
int main( int argc, char *argv[])
{
int s;
struct in_addr ipvalue;
printf("converting %s to network address \n", argv[1]);
s = inet_pton(AF_INET, argv[1], &ipvalue);
switch(s) {
case 1:
printf("converted value = %x \n", ipvalue.s_addr);
return 0;
case 0:
printf("invalid input: %s\n", argv[1]);
return 1;
default:
printf("inet_pton conversion error \n");
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5342 次 |
| 最近记录: |