2 * PROJECT: ReactOS netstat utility
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: base/applications/network/netstat/netstat.c
5 * PURPOSE: display IP stack statistics
6 * COPYRIGHT: Copyright 2005 Ged Murphy <gedmurphy@gmail.com>
10 * sort function return values.
11 * implement -b, -o and -v
12 * clean up GetIpHostName
13 * command line parser needs more work
16 #define WIN32_NO_STATUS
29 enum ProtoType
{IP
, TCP
, UDP
, ICMP
} Protocol
;
30 DWORD Interval
; /* time to pause between printing output */
32 /* TCP endpoint states */
33 TCHAR TcpState
[][32] = {
50 * format message string and display output
52 DWORD
DoFormatMessage(DWORD ErrorCode
)
57 if ((RetVal
= FormatMessage(
58 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
59 FORMAT_MESSAGE_FROM_SYSTEM
|
60 FORMAT_MESSAGE_IGNORE_INSERTS
,
63 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
), /* Default language */
68 _tprintf(_T("%s"), (LPTSTR
)lpMsgBuf
);
71 /* return number of TCHAR's stored in output buffer
72 * excluding '\0' - as FormatMessage does*/
81 * Parse command line parameters and set any options
84 BOOL
ParseCmdline(int argc
, char* argv
[])
90 if ((argc
== 1) || (_istdigit(*argv
[1])))
93 /* Parse command line for options we have been given. */
94 for (i
= 1; i
< argc
; i
++)
96 if ((argc
> 1) && (argv
[i
][0] == '-' || argv
[i
][0] == '/'))
98 while ((c
= *++argv
[i
]) != '\0')
103 bDoShowAllCons
= TRUE
;
106 bDoShowProcName
= TRUE
;
109 bDoShowEthStats
= TRUE
;
112 bDoShowNumbers
= TRUE
;
115 bDoShowProtoCons
= TRUE
;
117 if (!_stricmp("IP", Proto
))
119 else if (!_stricmp("ICMP", Proto
))
121 else if (!_stricmp("TCP", Proto
))
123 else if (!_stricmp("UDP", Proto
))
132 bDoShowRouteTable
= TRUE
;
135 bDoShowProtoStats
= TRUE
;
138 _tprintf(_T("got v\n"));
139 bDoDispSeqComp
= TRUE
;
147 else if (_istdigit(*argv
[i
]))
149 if (_stscanf(argv
[i
], "%lu", &Interval
) != EOF
)
165 * Simulate Microsofts netstat utility output
171 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
176 if (bDoShowRouteTable
)
178 /* mingw doesn't have lib for _tsystem */
179 if (system("route print") == -1)
181 _tprintf(_T("cannot find 'route.exe'\n"));
189 ShowEthernetStatistics();
193 if (bDoShowProtoCons
)
198 if (bDoShowProtoStats
)
205 if (bDoShowProtoStats
)
207 ShowIcmpStatistics();
212 if (bDoShowProtoStats
)
214 _tprintf(_T("\nActive Connections\n"));
215 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
219 if (bDoShowProtoStats
)
221 _tprintf(_T("\nActive Connections\n"));
222 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
229 else if (bDoShowProtoStats
)
232 ShowIcmpStatistics();
239 _tprintf(_T("\nActive Connections\n"));
240 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
248 VOID
ShowIpStatistics()
250 PMIB_IPSTATS pIpStats
;
253 pIpStats
= (MIB_IPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPSTATS
));
255 if ((dwRetVal
= GetIpStatistics(pIpStats
)) == NO_ERROR
)
257 _tprintf(_T("\nIPv4 Statistics\n\n"));
258 _tprintf(_T(" %-34s = %lu\n"), _T("Packets Received"), pIpStats
->dwInReceives
);
259 _tprintf(_T(" %-34s = %lu\n"), _T("Received Header Errors"), pIpStats
->dwInHdrErrors
);
260 _tprintf(_T(" %-34s = %lu\n"), _T("Received Address Errors"), pIpStats
->dwInAddrErrors
);
261 _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Forwarded"), pIpStats
->dwForwDatagrams
);
262 _tprintf(_T(" %-34s = %lu\n"), _T("Unknown Protocols Received"), pIpStats
->dwInUnknownProtos
);
263 _tprintf(_T(" %-34s = %lu\n"), _T("Received Packets Discarded"), pIpStats
->dwInDiscards
);
264 _tprintf(_T(" %-34s = %lu\n"), _T("Received Packets Delivered"), pIpStats
->dwInDelivers
);
265 _tprintf(_T(" %-34s = %lu\n"), _T("Output Requests"), pIpStats
->dwOutRequests
);
266 _tprintf(_T(" %-34s = %lu\n"), _T("Routing Discards"), pIpStats
->dwRoutingDiscards
);
267 _tprintf(_T(" %-34s = %lu\n"), _T("Discarded Output Packets"), pIpStats
->dwOutDiscards
);
268 _tprintf(_T(" %-34s = %lu\n"), _T("Output Packets No Route"), pIpStats
->dwOutNoRoutes
);
269 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Required"), pIpStats
->dwReasmReqds
);
270 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Succesful"), pIpStats
->dwReasmOks
);
271 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Failures"), pIpStats
->dwReasmFails
);
272 // _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams succesfully fragmented"), NULL); /* FIXME: what is this one? */
273 _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Failing Fragmentation"), pIpStats
->dwFragFails
);
274 _tprintf(_T(" %-34s = %lu\n"), _T("Fragments Created"), pIpStats
->dwFragCreates
);
277 DoFormatMessage(dwRetVal
);
279 HeapFree(GetProcessHeap(), 0, pIpStats
);
282 VOID
ShowIcmpStatistics()
284 PMIB_ICMP pIcmpStats
;
287 pIcmpStats
= (MIB_ICMP
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_ICMP
));
289 if ((dwRetVal
= GetIcmpStatistics(pIcmpStats
)) == NO_ERROR
)
291 _tprintf(_T("\nICMPv4 Statistics\n\n"));
292 _tprintf(_T(" Received Sent\n"));
293 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Messages"),
294 pIcmpStats
->stats
.icmpInStats
.dwMsgs
, pIcmpStats
->stats
.icmpOutStats
.dwMsgs
);
295 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Errors"),
296 pIcmpStats
->stats
.icmpInStats
.dwErrors
, pIcmpStats
->stats
.icmpOutStats
.dwErrors
);
297 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Destination Unreachable"),
298 pIcmpStats
->stats
.icmpInStats
.dwDestUnreachs
, pIcmpStats
->stats
.icmpOutStats
.dwDestUnreachs
);
299 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Time Exceeded"),
300 pIcmpStats
->stats
.icmpInStats
.dwTimeExcds
, pIcmpStats
->stats
.icmpOutStats
.dwTimeExcds
);
301 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Parameter Problems"),
302 pIcmpStats
->stats
.icmpInStats
.dwParmProbs
, pIcmpStats
->stats
.icmpOutStats
.dwParmProbs
);
303 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Source Quenches"),
304 pIcmpStats
->stats
.icmpInStats
.dwSrcQuenchs
, pIcmpStats
->stats
.icmpOutStats
.dwSrcQuenchs
);
305 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Redirects"),
306 pIcmpStats
->stats
.icmpInStats
.dwRedirects
, pIcmpStats
->stats
.icmpOutStats
.dwRedirects
);
307 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echos"),
308 pIcmpStats
->stats
.icmpInStats
.dwEchos
, pIcmpStats
->stats
.icmpOutStats
.dwEchos
);
309 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echo Replies"),
310 pIcmpStats
->stats
.icmpInStats
.dwEchoReps
, pIcmpStats
->stats
.icmpOutStats
.dwEchoReps
);
311 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamps"),
312 pIcmpStats
->stats
.icmpInStats
.dwTimestamps
, pIcmpStats
->stats
.icmpOutStats
.dwTimestamps
);
313 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamp Replies"),
314 pIcmpStats
->stats
.icmpInStats
.dwTimestampReps
, pIcmpStats
->stats
.icmpOutStats
.dwTimestampReps
);
315 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Masks"),
316 pIcmpStats
->stats
.icmpInStats
.dwAddrMasks
, pIcmpStats
->stats
.icmpOutStats
.dwAddrMasks
);
317 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Mask Replies"),
318 pIcmpStats
->stats
.icmpInStats
.dwAddrMaskReps
, pIcmpStats
->stats
.icmpOutStats
.dwAddrMaskReps
);
321 DoFormatMessage(dwRetVal
);
323 HeapFree(GetProcessHeap(), 0, pIcmpStats
);
327 VOID
ShowTcpStatistics()
329 PMIB_TCPSTATS pTcpStats
;
332 pTcpStats
= (MIB_TCPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_TCPSTATS
));
334 if ((dwRetVal
= GetTcpStatistics(pTcpStats
)) == NO_ERROR
)
336 _tprintf(_T("\nTCP Statistics for IPv4\n\n"));
337 _tprintf(_T(" %-35s = %lu\n"), _T("Active Opens"), pTcpStats
->dwActiveOpens
);
338 _tprintf(_T(" %-35s = %lu\n"), _T("Passive Opens"), pTcpStats
->dwPassiveOpens
);
339 _tprintf(_T(" %-35s = %lu\n"), _T("Failed Connection Attempts"), pTcpStats
->dwAttemptFails
);
340 _tprintf(_T(" %-35s = %lu\n"), _T("Reset Connections"), pTcpStats
->dwEstabResets
);
341 _tprintf(_T(" %-35s = %lu\n"), _T("Current Connections"), pTcpStats
->dwCurrEstab
);
342 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Received"), pTcpStats
->dwInSegs
);
343 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Sent"), pTcpStats
->dwOutSegs
);
344 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Retransmitted"), pTcpStats
->dwRetransSegs
);
347 DoFormatMessage(dwRetVal
);
349 HeapFree(GetProcessHeap(), 0, pTcpStats
);
352 VOID
ShowUdpStatistics()
354 PMIB_UDPSTATS pUdpStats
;
357 pUdpStats
= (MIB_UDPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_UDPSTATS
));
359 if ((dwRetVal
= GetUdpStatistics(pUdpStats
)) == NO_ERROR
)
361 _tprintf(_T("\nUDP Statistics for IPv4\n\n"));
362 _tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Received"), pUdpStats
->dwInDatagrams
);
363 _tprintf(_T(" %-21s = %lu\n"), _T("No Ports"), pUdpStats
->dwNoPorts
);
364 _tprintf(_T(" %-21s = %lu\n"), _T("Receive Errors"), pUdpStats
->dwInErrors
);
365 _tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Sent"), pUdpStats
->dwOutDatagrams
);
368 DoFormatMessage(dwRetVal
);
370 HeapFree(GetProcessHeap(), 0, pUdpStats
);
373 VOID
ShowEthernetStatistics()
375 PMIB_IFTABLE pIfTable
;
379 pIfTable
= (MIB_IFTABLE
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IFTABLE
));
381 if (GetIfTable(pIfTable
, &dwSize
, 0) == ERROR_INSUFFICIENT_BUFFER
)
383 HeapFree(GetProcessHeap(), 0, pIfTable
);
384 pIfTable
= (MIB_IFTABLE
*) HeapAlloc(GetProcessHeap(), 0, dwSize
);
386 if ((dwRetVal
= GetIfTable(pIfTable
, &dwSize
, 0)) == NO_ERROR
)
388 _tprintf(_T("Interface Statistics\n\n"));
389 _tprintf(_T(" Received Sent\n\n"));
390 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Bytes"),
391 pIfTable
->table
[0].dwInOctets
, pIfTable
->table
[0].dwOutOctets
);
392 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Unicast packets"),
393 pIfTable
->table
[0].dwInUcastPkts
, pIfTable
->table
[0].dwOutUcastPkts
);
394 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Non-unicast packets"),
395 pIfTable
->table
[0].dwInNUcastPkts
, pIfTable
->table
[0].dwOutNUcastPkts
);
396 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Discards"),
397 pIfTable
->table
[0].dwInDiscards
, pIfTable
->table
[0].dwOutDiscards
);
398 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Errors"),
399 pIfTable
->table
[0].dwInErrors
, pIfTable
->table
[0].dwOutErrors
);
400 _tprintf(_T("%-20s %14lu\n"), _T("Unknown Protocols"),
401 pIfTable
->table
[0].dwInUnknownProtos
);
404 DoFormatMessage(dwRetVal
);
406 HeapFree(GetProcessHeap(), 0, pIfTable
);
411 PMIB_TCPTABLE tcpTable
;
414 CHAR HostIp
[HOSTNAMELEN
], HostPort
[PORTNAMELEN
];
415 CHAR RemoteIp
[HOSTNAMELEN
], RemotePort
[PORTNAMELEN
];
416 CHAR Host
[ADDRESSLEN
];
417 CHAR Remote
[ADDRESSLEN
];
419 /* Get the table of TCP endpoints */
420 dwSize
= sizeof (MIB_TCPTABLE
);
421 /* Should also work when we get new connections between 2 GetTcpTable()
425 tcpTable
= (PMIB_TCPTABLE
) HeapAlloc(GetProcessHeap(), 0, dwSize
);
426 error
= GetTcpTable(tcpTable
, &dwSize
, TRUE
);
427 if ( error
!= NO_ERROR
)
428 HeapFree(GetProcessHeap(), 0, tcpTable
);
430 while ( error
== ERROR_INSUFFICIENT_BUFFER
);
432 if (error
!= NO_ERROR
)
434 printf("Failed to snapshot TCP endpoints.\n");
435 DoFormatMessage(error
);
439 /* Dump the TCP table */
440 for (i
= 0; i
< tcpTable
->dwNumEntries
; i
++)
442 /* If we aren't showing all connections, only display established, close wait
443 * and time wait. This is the default output for netstat */
444 if (bDoShowAllCons
|| (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_ESTAB
)
445 || (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_CLOSE_WAIT
)
446 || (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_TIME_WAIT
))
448 /* I've split this up so it's easier to follow */
449 GetIpHostName(TRUE
, tcpTable
->table
[i
].dwLocalAddr
, HostIp
, HOSTNAMELEN
);
450 GetPortName(tcpTable
->table
[i
].dwLocalPort
, "tcp", HostPort
, PORTNAMELEN
);
451 sprintf(Host
, "%s:%s", HostIp
, HostPort
);
453 if (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_LISTEN
)
455 sprintf(Remote
, "%s:0", HostIp
);
459 GetIpHostName(FALSE
, tcpTable
->table
[i
].dwRemoteAddr
, RemoteIp
, HOSTNAMELEN
);
460 GetPortName(tcpTable
->table
[i
].dwRemotePort
, "tcp", RemotePort
, PORTNAMELEN
);
461 sprintf(Remote
, "%s:%s", RemoteIp
, RemotePort
);
464 _tprintf(_T(" %-6s %-22s %-22s %s\n"), _T("TCP"),
465 Host
, Remote
, TcpState
[tcpTable
->table
[i
].dwState
]);
468 HeapFree(GetProcessHeap(), 0, tcpTable
);
473 PMIB_UDPTABLE udpTable
;
476 CHAR HostIp
[HOSTNAMELEN
], HostPort
[PORTNAMELEN
];
477 CHAR Host
[ADDRESSLEN
];
479 /* Get the table of UDP endpoints */
481 error
= GetUdpTable(NULL
, &dwSize
, TRUE
);
482 if (error
!= ERROR_INSUFFICIENT_BUFFER
)
484 printf("Failed to snapshot UDP endpoints.\n");
485 DoFormatMessage(error
);
488 udpTable
= (PMIB_UDPTABLE
) HeapAlloc(GetProcessHeap(), 0, dwSize
);
489 error
= GetUdpTable(udpTable
, &dwSize
, TRUE
);
492 printf("Failed to snapshot UDP endpoints table.\n");
493 DoFormatMessage(error
);
494 HeapFree(GetProcessHeap(), 0, udpTable
);
498 /* Dump the UDP table */
499 for (i
= 0; i
< udpTable
->dwNumEntries
; i
++)
502 /* I've split this up so it's easier to follow */
503 GetIpHostName(TRUE
, udpTable
->table
[i
].dwLocalAddr
, HostIp
, HOSTNAMELEN
);
504 GetPortName(udpTable
->table
[i
].dwLocalPort
, "tcp", HostPort
, PORTNAMELEN
);
506 sprintf(Host
, "%s:%s", HostIp
, HostPort
);
508 _tprintf(_T(" %-6s %-22s %-22s\n"), _T("UDP"), Host
, _T("*:*"));
511 HeapFree(GetProcessHeap(), 0, udpTable
);
515 * Translate port numbers into their text equivalent if there is one
518 GetPortName(UINT Port
, PCSTR Proto
, CHAR Name
[], INT NameLen
)
520 struct servent
*pSrvent
;
524 sprintf(Name
, "%d", htons((WORD
)Port
));
527 /* Try to translate to a name */
528 if ((pSrvent
= getservbyport(Port
, Proto
)))
529 strcpy(Name
, pSrvent
->s_name
);
531 sprintf(Name
, "%d", htons((WORD
)Port
));
536 * convert addresses into dotted decimal or hostname
539 GetIpHostName(BOOL Local
, UINT IpAddr
, CHAR Name
[], int NameLen
)
541 // struct hostent *phostent;
544 /* display dotted decimal */
545 nIpAddr
= htonl(IpAddr
);
546 if (bDoShowNumbers
) {
547 sprintf(Name
, "%d.%d.%d.%d",
548 (nIpAddr
>> 24) & 0xFF,
549 (nIpAddr
>> 16) & 0xFF,
550 (nIpAddr
>> 8) & 0xFF,
557 /* try to resolve the name */
560 sprintf(Name
, "%d.%d.%d.%d",
561 (nIpAddr
>> 24) & 0xFF,
562 (nIpAddr
>> 16) & 0xFF,
563 (nIpAddr
>> 8) & 0xFF,
566 if (gethostname(Name
, NameLen
) != 0)
567 DoFormatMessage(WSAGetLastError());
569 } else if (IpAddr
== 0x0100007f) {
571 if (gethostname(Name
, NameLen
) != 0)
572 DoFormatMessage(WSAGetLastError());
574 _tcsncpy(Name
, _T("localhost"), 10);
576 // } else if (phostent = gethostbyaddr((char*)&ipaddr, sizeof(nipaddr), PF_INET)) {
577 // strcpy(name, phostent->h_name);
579 sprintf(Name
, "%d.%d.%d.%d",
580 ((nIpAddr
>> 24) & 0x000000FF),
581 ((nIpAddr
>> 16) & 0x000000FF),
582 ((nIpAddr
>> 8) & 0x000000FF),
583 ((nIpAddr
) & 0x000000FF));
590 _tprintf(_T("\nDisplays current TCP/IP protocol statistics and network connections.\n\n"
591 "NETSTAT [-a] [-e] [-n] [-p proto] [-r] [-s] [interval]\n\n"
592 " -a Displays all connections and listening ports.\n"
593 " -e Displays Ethernet statistics. May be combined with -s\n"
595 " -n Displays address and port numbers in numeric form.\n"
596 " -p proto Shows connections for protocol 'proto' TCP or UDP.\n"
597 " If used with the -s option to display\n"
598 " per-protocol statistics, 'proto' may be TCP, UDP, or IP.\n"
599 " -r Displays the current routing table.\n"
600 " -s Displays per-protocol statistics. By default, Statistics are\n"
601 " shown for IP, ICMP, TCP and UDP;\n"
602 " the -p option may be used to specify a subset of the default.\n"
603 " interval Redisplays selected statistics every 'interval' seconds.\n"
604 " Press CTRL+C to stop redisplaying. By default netstat will\n"
605 " print the current information only once.\n"));
610 * Parse command line parameters and set any options
611 * Run display output, looping over set intervals if a number is given
614 int main(int argc
, char *argv
[])
618 if (WSAStartup(MAKEWORD(2, 2), &wsaData
) != 0)
620 _tprintf(_T("WSAStartup() failed : %d\n"), WSAGetLastError());
624 if (ParseCmdline(argc
, argv
))
633 Sleep(Interval
*1000);