Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: access structure field through its name in a string

In Scapy, I want to compare a number of header fields between any two packets a and b. This list of fields is predefined, say:

fieldsToCompare = ['tos', 'id', 'len', 'proto'] #IP header

Normally I would do it individually:

if a[IP].tos == b[IP].tos:
   ... do stuff...

Is there any way to access those packet fields from a list of strings including what each one of them is called? Like:

for field in fieldsToCompare:
    if a[IP].field == b[IP].field:
         ... do stuff...
like image 996
Ricky Robinson Avatar asked Apr 17 '13 12:04

Ricky Robinson


Video Answer


1 Answers

You can use getattr(). These lines are equivalent:

getattr(x, 'foobar')
x.foobar

setattr() is its counterpart.

like image 119
Gareth Webber Avatar answered Oct 01 '22 13:10

Gareth Webber