1

Using Python on Linux: I have a TCPSocket server that I would like to listen on eth0, and no other interfaces. If eth0 has no address, the socket should not listen at all.

I can bind to the IP address associated with eth0, but if that address changes, my socket will no longer receive connections. There appears to be no simple way to receive notifications of IP address changes.

I could poll the IP address of eth0, and bind the socket to the new address when it changes. Is there a better way of implementing this?

I explored SO_BINDTODEVICE but this requires root privileges.

ridiculous_fish
  • 17,273
  • 1
  • 54
  • 61
  • Can you get ip of eth0 before you start socket in your code? – Stephen Lin Jul 16 '14 at 23:09
  • The most upvoted answer in this question shows how you can monitor address changes on Linux using AF_NETLINK sockets in C: http://stackoverflow.com/questions/579783/how-to-detect-ip-address-change-programmatically-in-linux – Ross Ridge Jul 16 '14 at 23:43

1 Answers1

0

Seems you have two solutions, as you said:

  1. Poll to get IPs of your interface, restart your server when it changes.

  2. Listen for events indicating your IP has changed using netlink (man 7 netlink)

You may find examples of code using netlink by searching RTMGRP_IPV4_IFADDR (IPv4 addresses add/delete events) on github.

Julien Palard
  • 8,736
  • 2
  • 37
  • 44