ping: if -S srcaddr uses a numeric address, use that protocol

The command "ping -S dotted.quad hostname" fails on dual-stack hosts
with the confusing message "ping: invalid source address: Name does
not resolve" because IPv6 is selected in preference.  If the argument
to -S is numeric (likely), select the corresponding address family,
as if -4 or -6 was specified.  Add tests that either IPv4 or IPv6 can
be forced via a -S parameter.

Reviewed by:	asomers
Differential Revision: https://reviews.freebsd.org/D35271
MFC after:	1 week
This commit is contained in:
Mike Karels 2022-05-20 09:16:01 -05:00
parent 72bf76d6b8
commit 5af718a592
4 changed files with 50 additions and 0 deletions

View file

@ -93,6 +93,18 @@ main(int argc, char *argv[])
case '6':
ipv6 = true;
break;
#endif
#if defined(INET) && defined(INET6)
case 'S':
/*
* If -S is given with a numeric parameter,
* force use of the corresponding version.
*/
if (inet_pton(AF_INET, optarg, &a) == 1)
ipv4 = true;
else if (inet_pton(AF_INET6, optarg, &a) == 1)
ipv6 = true;
break;
#endif
default:
break;

View file

@ -0,0 +1,6 @@
PING localhost from: 56 data bytes
64 bytes from: icmp_seq=0 ttl= time= ms
--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = /// ms

View file

@ -0,0 +1,6 @@
PING6(56=40+8+8 bytes) ::1 --> ::1
16 bytes from ::1, icmp_seq=0 hlim= time= ms
--- localhost ping6 statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/std-dev = /// ms

View file

@ -49,6 +49,18 @@ ping_c1_s56_t1_body() {
check_ping_statistics std.out $(atf_get_srcdir)/ping_c1_s56_t1.out
}
atf_test_case ping_c1_s56_t1_S127
ping_c1_s56_t1_S127_head() {
atf_set "descr" "Check that ping -S 127.0.0.1 localhost succeeds"
}
ping_c1_s56_t1_S127_body() {
require_ipv4
require_ipv6
atf_check -s exit:0 -o save:std.out -e empty \
ping -c 1 -s 56 -t 1 -S 127.0.0.1 localhost
check_ping_statistics std.out $(atf_get_srcdir)/ping_c1_s56_t1_S127.out
}
atf_test_case ping_6_c1_s8_t1
ping_6_c1_s8_t1_head() {
atf_set "descr" "Stop after receiving 1 ECHO_RESPONSE packet"
@ -60,6 +72,18 @@ ping_6_c1_s8_t1_body() {
check_ping_statistics std.out $(atf_get_srcdir)/ping_6_c1_s8_t1.out
}
atf_test_case ping_c1_s8_t1_S1
ping_c1_s8_t1_S1_head() {
atf_set "descr" "Check that ping -S ::1 localhost succeeds"
}
ping_c1_s8_t1_S1_body() {
require_ipv4
require_ipv6
atf_check -s exit:0 -o save:std.out -e empty \
ping -c 1 -s 8 -t 1 -S ::1 localhost
check_ping_statistics std.out $(atf_get_srcdir)/ping_c1_s8_t1_S1.out
}
atf_test_case ping6_c1_s8_t1
ping6_c1_s8_t1_head() {
atf_set "descr" "Use IPv6 when invoked as ping6"
@ -104,7 +128,9 @@ ping6_46_body() {
atf_init_test_cases() {
atf_add_test_case ping_c1_s56_t1
atf_add_test_case ping_c1_s56_t1_S127
atf_add_test_case ping_6_c1_s8_t1
atf_add_test_case ping_c1_s8_t1_S1
atf_add_test_case ping6_c1_s8_t1
atf_add_test_case ping_c1t6
atf_add_test_case ping6_c1t4