我想通过键盘使用整数和点手动输入IP地址 代码应该自动检查天气,点之间的整数范围从0到255
这是来自互联网的示例代码 一切都很完美,但我希望有机会手动输入IP地址,而不是使用预定义的IP地址
/* Sample code from Techpulp.
* You are free to use this source code as you wish.
* However Techpulp provides no warranty that this code works ans claims no responsibility for any damage.
* Author: neo@techpulp.com
* http://www.techpulp.com/
*/
#include <stdio.h>
#include <unistd.h>
int is_valid_ip(const char *ip_str)
{
unsigned int n1,n2,n3,n4;
if(sscanf(ip_str,"%u.%u.%u.%u", &n1, &n2, &n3, &n4) != 4) return 0;
if((n1 != 0) && (n1 <= 255) && (n2 <= 255) && (n3 <= 255) && (n4 <= 255)) {
char buf[64];
sprintf(buf,"%u.%u.%u.%u",n1,n2,n3,n4);
if(strcmp(buf,ip_str)) return 0;
return 1;
}
return 0;
}
char *test_ips[] = {
"1.1.1.1",
"255.255.255.255",
"0.123.234.12",
"1.255.4.5",
"127.8.190.29",
"3hu23e832j2....wjdnw",
"3a.3b.2d.5t",
"-1.-1.-1.-1",
"1.1.1.1.3",
NULL
};
int main(int argc, char *argv[])
{
int i = 0;
printf("\n------------------------------------------\n");
printf("IP Address Validation\n");
printf("------------------------------------------\n");
while(test_ips[i]) {
printf("%20s\t%s\n",
test_ips[i],
is_valid_ip(test_ips[i])?"VALID ":"INVALID "
);
i++;
}
printf("------------------------------------------\n\n");
return 0;
}
答案 0 :(得分:1)
使用scanf或fgets从标准输入/键盘读取值。
答案 1 :(得分:1)
E.g
int main(void){
char input[32];
printf("input IP Address : ");
scanf("%s", input);
printf("%s\t%s\n",
input,
is_valid_ip(input)?"VALID ":"INVALID "
);
return 0;
}
答案 2 :(得分:1)
用scanf替换sscanf。
if(sscanf(ip_str,"%u.%u.%u.%u", &n1, &n2, &n3, &n4) != 4) return 0;
将成为
if(scanf(ip_str,"%u.%u.%u.%u", &n1, &n2, &n3, &n4) != 4) return 0;
或使用你喜欢的任何来自stdin的函数。