2

I want to ping a target IP address, using a specific interface with Python.

One possibility would be to import os and use the system's ping command.

import os
hostname = "127.0.0.1"
interface = "eth0"
response = os.system("ping -c 2 -I " + interface + " " + hostname)

if response == 0:
  print("up")
else:
  print("down")

Is there a more OS independent way to ping a target IP, using a specific interface with python?

edit: The suggested duplicate question does not discuss specific interfaces, nor platform independence. Many of the answers reflect the option I've shown in my question.

On a side note, I'd rather not import non-standard python classes.

SaAtomic
  • 619
  • 1
  • 12
  • 29
  • Possible duplicate of [Ping a site in Python?](http://stackoverflow.com/questions/316866/ping-a-site-in-python) – Luke Worth Mar 30 '17 at 06:26
  • **a-** detect platform. Call `ping` utility with appropriate options for the platform¶ **b-** bind a raw socket to an ip that corresponds to the desirable network interface (the implementation of net_if -> ip function may depend on platform), make icmp requests to implement the ping functionality¶ **c-** use a 3-rd party module that does either a- or b- for you. – jfs Mar 30 '17 at 13:26

1 Answers1

0

I had the same need and found a way!

https://github.com/kyan001/ping3

It has the option src_addr where you can specify the interface you want to use.

  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30865571) – Simas Joneliunas Jan 24 '22 at 04:45