Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6685703
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T05:05:15+00:00 2026-05-26T05:05:15+00:00

There is a socket method for getting the IP of a given network interface:

  • 0

There is a socket method for getting the IP of a given network interface:

import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

Which returns the following:

>>> get_ip_address('lo')
'127.0.0.1'

>>> get_ip_address('eth0')
'38.113.228.130'

Is there a similar method to return the network transfer of that interface? I know I can read /proc/net/dev but I’d love a socket method.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T05:05:16+00:00Added an answer on May 26, 2026 at 5:05 am

    The best way to poll ethernet interface statistics is through SNMP…

    • It looks like you’re using linux… if so, load up your snmpd with these options… after installing snmpd, in your /etc/defaults/snmpd (make sure the line with SNMPDOPTS looks like this):

      SNMPDOPTS='-Lsd -Lf /dev/null -u snmp -I -smux,usmConf,iquery,dlmod,diskio,lmSensors,hr_network,snmpEngine,system_mib,at,interface,ifTable,ipAddressTable,ifXTable,ip,cpu,tcpTable,udpTable,ipSystemStatsTable,ip,snmp_mib,tcp,icmp,udp,proc,memory,snmpNotifyTable,inetNetToMediaTable,ipSystemStatsTable,disk -Lsd -p /var/run/snmpd.pid'

    • You might also need to change the ro community to public See Note 1 and set your listening interfaces in /etc/snmp/snmpd.conf (if not on the loopback)…

    • Assuming you have a functional snmpd, at this point, you can poll ifHCInBytes and ifHCOutBytes See Note 2 for your interface(s) in question using this…

    poll_bytes.py:

    from SNMP import v2Manager
    import time
    
    def poll_eth0(manager=None):
        # NOTE: 2nd arg to get_index should be a valid ifName value
        in_bytes = manager.get_index('ifHCInOctets', 'eth0')
        out_bytes = manager.get_index('ifHCOutOctets', 'eth0')
        return (time.time(), int(in_bytes), int(out_bytes))
    
    # Prep an SNMP manager object...
    mgr = v2Manager('localhost')
    mgr.index('ifName')
    stats = list()
    # Insert condition below, instead of True...
    while True:
        stats.append(poll_eth0(mgr))
        print poll_eth0(mgr)
        time.sleep(5)
    

    SNMP.py:

    from subprocess import Popen, PIPE
    import re
    
    class v2Manager(object):
        def __init__(self, addr='127.0.0.1', community='public'):
            self.addr      = addr
            self.community = community
            self._index = dict()
    
        def bulkwalk(self, oid='ifName'):
            cmd = 'snmpbulkwalk -v 2c -Osq -c %s %s %s' % (self.community,
                self.addr, oid)
            po = Popen(cmd, shell=True, stdout=PIPE, executable='/bin/bash')
            output = po.communicate()[0]
            result = dict()
            for line in re.split(r'\r*\n', output):
                if line.strip()=="":
                    continue
                idx, value = re.split(r'\s+', line, 1)
                idx = idx.replace(oid+".", '')
                result[idx] = value
            return result
    
        def bulkwalk_index(self, oid='ifOutOctets'):
            result = dict()
            if not (self._index==dict()):
                vals = self.bulkwalk(oid=oid)
                for key, val in vals.items():
                    idx = self._index.get(key, None)
                    if not (idx is None):
                        result[idx] = val
                    else:
                        raise ValueError, "Could not find '%s' in the index (%s)" % self.index
            else:
                raise ValueError, "Call the index() method before calling bulkwalk_index()"
            return result
    
        def get_index(self, oid='ifOutOctets', index=''):
            # This method is horribly inefficient... improvement left as exercise for the reader...
            if index:
                return self.bulkwalk_index().get(index, "<unknown>")
            else:
                raise ValueError, "Please include an index to get"
    
        def index(self, oid='ifName'):
            self._index = self.bulkwalk(oid=oid)
    

    END NOTES:

    1. SNMP v2c uses clear-text authentication. If you are worried about security / someone sniffing your traffic, change your community and restrict queries to your linux machine by source ip address. The perfect world would be to modify the SNMP.py above to use SNMPv3 (which encrypts sensitive data); most people just use a non-public community and restrict snmp queries by source IP.

    2. ifHCInOctets and ifHCOutOctets provide instantaneous values for the number of bytes transferred through the interface. If you are looking for data transfer rate, of course there will be some additional math involved.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

There doesn't seem to be any method of Socket, or ListenSocket that will allow
There is a socket related function call in my code, that function is from
Is there a way to get a list of all open sockets ( socket
Is there any way to open a broadcast bluetooth socket, take a listen and
Is there a way to only close one end of a TCP socket to
Is there a standard call for flushing the transmit side of a POSIX socket
I'm wondering whether there is a way to poll a socket in c# when
Using UNIX socket APIs on Linux, is there any way to guarantee that I
When reading from a IO::Socket::INET filehandle it can not be assumed that there will
I have a DataInputStream that I obtained from a Socket . Is there any

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.