@@ -52,7 +52,7 @@ psutil_get_nic_addresses(void) {
5252PyObject *
5353psutil_net_io_counters (PyObject * self , PyObject * args ) {
5454 DWORD dwRetVal = 0 ;
55- MIB_IF_ROW2 * pIfRow = NULL ;
55+ MIB_IF_ROW2 ifRow ;
5656 PIP_ADAPTER_ADDRESSES pAddresses = NULL ;
5757 PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL ;
5858 PyObject * py_retdict = PyDict_New ();
@@ -64,68 +64,64 @@ psutil_net_io_counters(PyObject *self, PyObject *args) {
6464 pAddresses = psutil_get_nic_addresses ();
6565 if (pAddresses == NULL )
6666 goto error ;
67+
6768 pCurrAddresses = pAddresses ;
6869
6970 while (pCurrAddresses ) {
70- py_nic_name = NULL ;
7171 py_nic_info = NULL ;
72+ py_nic_name = NULL ;
7273
73- pIfRow = (MIB_IF_ROW2 * )malloc (sizeof (MIB_IF_ROW2 ));
74- if (pIfRow == NULL ) {
75- PyErr_NoMemory ();
76- goto error ;
77- }
74+ SecureZeroMemory (& ifRow , sizeof (ifRow ));
75+ ifRow .InterfaceIndex = pCurrAddresses -> IfIndex ;
7876
79- SecureZeroMemory ((PVOID )pIfRow , sizeof (MIB_IF_ROW2 ));
80- pIfRow -> InterfaceIndex = pCurrAddresses -> IfIndex ;
81- dwRetVal = GetIfEntry2 (pIfRow );
77+ dwRetVal = GetIfEntry2 (& ifRow );
8278 if (dwRetVal != NO_ERROR ) {
8379 psutil_runtime_error (
84- "GetIfEntry() or GetIfEntry2() syscalls failed."
80+ "GetIfEntry2() syscall failed for interface %lu" ,
81+ (unsigned long )ifRow .InterfaceIndex
8582 );
8683 goto error ;
8784 }
8885
8986 py_nic_info = Py_BuildValue (
9087 "(KKKKKKKK)" ,
91- pIfRow -> OutOctets ,
92- pIfRow -> InOctets ,
93- ( pIfRow -> OutUcastPkts + pIfRow -> OutNUcastPkts ) ,
94- ( pIfRow -> InUcastPkts + pIfRow -> InNUcastPkts ) ,
95- pIfRow -> InErrors ,
96- pIfRow -> OutErrors ,
97- pIfRow -> InDiscards ,
98- pIfRow -> OutDiscards
88+ ifRow . OutOctets ,
89+ ifRow . InOctets ,
90+ ifRow . OutUcastPkts + ifRow . OutNUcastPkts ,
91+ ifRow . InUcastPkts + ifRow . InNUcastPkts ,
92+ ifRow . InErrors ,
93+ ifRow . OutErrors ,
94+ ifRow . InDiscards ,
95+ ifRow . OutDiscards
9996 );
10097 if (!py_nic_info )
10198 goto error ;
10299
103100 py_nic_name = PyUnicode_FromWideChar (
104- pCurrAddresses -> FriendlyName , wcslen (pCurrAddresses -> FriendlyName )
101+ pCurrAddresses -> FriendlyName ,
102+ wcsnlen (pCurrAddresses -> FriendlyName , IF_MAX_STRING_SIZE )
105103 );
106-
107- if (py_nic_name == NULL )
104+ if (!py_nic_name )
108105 goto error ;
106+
109107 if (PyDict_SetItem (py_retdict , py_nic_name , py_nic_info ))
110108 goto error ;
111- Py_CLEAR ( py_nic_name );
109+
112110 Py_CLEAR (py_nic_info );
111+ Py_CLEAR (py_nic_name );
113112
114- free (pIfRow );
115113 pCurrAddresses = pCurrAddresses -> Next ;
116114 }
117115
118116 free (pAddresses );
119117 return py_retdict ;
120118
121119error :
122- Py_XDECREF (py_nic_name );
123120 Py_XDECREF (py_nic_info );
121+ Py_XDECREF (py_nic_name );
124122 Py_DECREF (py_retdict );
125- if (pAddresses != NULL )
123+ if (pAddresses )
126124 free (pAddresses );
127- if (pIfRow != NULL )
128- free (pIfRow );
129125 return NULL ;
130126}
131127
0 commit comments