2 * PROJECT: ReactOS netstat utility
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: apps/utils/net/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
24 enum ProtoType
{IP
, TCP
, UDP
, ICMP
} Protocol
;
25 DWORD Interval
; /* time to pause between printing output */
27 /* TCP endpoint states */
28 TCHAR TcpState
[][32] = {
46 * format message string and display output
48 DWORD
DoFormatMessage(DWORD ErrorCode
)
53 if ((RetVal
= FormatMessage(
54 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
55 FORMAT_MESSAGE_FROM_SYSTEM
|
56 FORMAT_MESSAGE_IGNORE_INSERTS
,
59 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
), /* Default language */
64 _tprintf(_T("%s"), (LPTSTR
)lpMsgBuf
);
67 /* return number of TCHAR's stored in output buffer
68 * excluding '\0' - as FormatMessage does*/
78 * Parse command line parameters and set any options
81 BOOL
ParseCmdline(int argc
, char* argv
[])
87 if ((argc
== 1) || (_istdigit(*argv
[1])))
90 /* Parse command line for options we have been given. */
91 for (i
= 1; i
< argc
; i
++)
93 if ( (argc
> 1)&&(argv
[i
][0] == '-') )
97 while ((c
= *++argv
[i
]) != '\0')
102 bDoShowAllCons
= TRUE
;
105 bDoShowProcName
= TRUE
;
108 bDoShowEthStats
= TRUE
;
111 bDoShowNumbers
= TRUE
;
114 bDoShowProtoStats
= TRUE
;
117 bDoShowProtoCons
= TRUE
;
119 strncpy(Proto
, (++argv
)[i
], sizeof(Proto
));
120 if (!_tcsicmp( "IP", Proto
))
122 else if (!_tcsicmp( "ICMP", Proto
))
124 else if (!_tcsicmp( "TCP", Proto
))
126 else if (!_tcsicmp( "UDP", Proto
))
133 --i
; /* move pointer back down to previous argv */
136 bDoShowRouteTable
= TRUE
;
139 _tprintf(_T("got v\n"));
140 bDoDispSeqComp
= TRUE
;
148 else if (_istdigit(*argv
[i
]))
150 if (_stscanf(argv
[i
], "%lu", &Interval
) != EOF
)
167 * Simulate Microsofts netstat utility output
173 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
178 if (bDoShowRouteTable
)
180 /* mingw doesn't have lib for _tsystem */
181 if (system("route print") == -1)
183 _tprintf(_T("cannot find 'route.exe'\n"));
191 ShowEthernetStatistics();
195 if (bDoShowProtoCons
)
200 if (bDoShowProtoStats
)
207 if (bDoShowProtoStats
)
209 ShowIcmpStatistics();
214 if (bDoShowProtoStats
)
216 _tprintf(_T("\nActive Connections\n"));
217 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
221 if (bDoShowProtoStats
)
223 _tprintf(_T("\nActive Connections\n"));
224 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
231 else if (bDoShowProtoStats
)
234 ShowIcmpStatistics();
239 else //if (bDoShowAllCons)
241 _tprintf(_T("\nActive Connections\n"));
242 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
252 VOID
ShowIpStatistics()
254 PMIB_IPSTATS pIpStats
;
257 pIpStats
= (MIB_IPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPSTATS
));
259 if ((dwRetVal
= GetIpStatistics(pIpStats
)) == NO_ERROR
)
261 _tprintf(_T("\nIPv4 Statistics\n\n"));
262 _tprintf(_T(" %-34s = %lu\n"), _T("Packets Recieved"), pIpStats
->dwInReceives
);
263 _tprintf(_T(" %-34s = %lu\n"), _T("Received Header Errors"), pIpStats
->dwInHdrErrors
);
264 _tprintf(_T(" %-34s = %lu\n"), _T("Received Address Errors"), pIpStats
->dwInAddrErrors
);
265 _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Forwarded"), pIpStats
->dwForwDatagrams
);
266 _tprintf(_T(" %-34s = %lu\n"), _T("Unknown Protocols Recieved"), pIpStats
->dwInUnknownProtos
);
267 _tprintf(_T(" %-34s = %lu\n"), _T("Received Packets Discarded"), pIpStats
->dwInDiscards
);
268 _tprintf(_T(" %-34s = %lu\n"), _T("Recieved Packets Delivered"), pIpStats
->dwInDelivers
);
269 _tprintf(_T(" %-34s = %lu\n"), _T("Output Requests"), pIpStats
->dwOutRequests
);
270 _tprintf(_T(" %-34s = %lu\n"), _T("Routing Discards"), pIpStats
->dwRoutingDiscards
);
271 _tprintf(_T(" %-34s = %lu\n"), _T("Discarded Output Packets"), pIpStats
->dwOutDiscards
);
272 _tprintf(_T(" %-34s = %lu\n"), _T("Output Packets No Route"), pIpStats
->dwOutNoRoutes
);
273 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Required"), pIpStats
->dwReasmReqds
);
274 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Succesful"), pIpStats
->dwReasmOks
);
275 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Failures"), pIpStats
->dwReasmFails
);
276 // _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams succesfully fragmented"), NULL); /* FIXME: what is this one? */
277 _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Failing Fragmentation"), pIpStats
->dwFragFails
);
278 _tprintf(_T(" %-34s = %lu\n"), _T("Fragments Created"), pIpStats
->dwFragCreates
);
281 DoFormatMessage(dwRetVal
);
283 HeapFree(GetProcessHeap(), 0, pIpStats
);
286 VOID
ShowIcmpStatistics()
288 PMIB_ICMP pIcmpStats
;
291 pIcmpStats
= (MIB_ICMP
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_ICMP
));
293 if ((dwRetVal
= GetIcmpStatistics(pIcmpStats
)) == NO_ERROR
)
295 _tprintf(_T("\nICMPv4 Statistics\n\n"));
296 _tprintf(_T(" Received Sent\n"));
297 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Messages"),
298 pIcmpStats
->stats
.icmpInStats
.dwMsgs
, pIcmpStats
->stats
.icmpOutStats
.dwMsgs
);
299 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Errors"),
300 pIcmpStats
->stats
.icmpInStats
.dwErrors
, pIcmpStats
->stats
.icmpOutStats
.dwErrors
);
301 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Destination Unreachable"),
302 pIcmpStats
->stats
.icmpInStats
.dwDestUnreachs
, pIcmpStats
->stats
.icmpOutStats
.dwDestUnreachs
);
303 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Time Exceeded"),
304 pIcmpStats
->stats
.icmpInStats
.dwTimeExcds
, pIcmpStats
->stats
.icmpOutStats
.dwTimeExcds
);
305 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Parameter Problems"),
306 pIcmpStats
->stats
.icmpInStats
.dwParmProbs
, pIcmpStats
->stats
.icmpOutStats
.dwParmProbs
);
307 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Source Quenches"),
308 pIcmpStats
->stats
.icmpInStats
.dwSrcQuenchs
, pIcmpStats
->stats
.icmpOutStats
.dwSrcQuenchs
);
309 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Redirects"),
310 pIcmpStats
->stats
.icmpInStats
.dwRedirects
, pIcmpStats
->stats
.icmpOutStats
.dwRedirects
);
311 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echos"),
312 pIcmpStats
->stats
.icmpInStats
.dwEchos
, pIcmpStats
->stats
.icmpOutStats
.dwEchos
);
313 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echo Replies"),
314 pIcmpStats
->stats
.icmpInStats
.dwEchoReps
, pIcmpStats
->stats
.icmpOutStats
.dwEchoReps
);
315 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamps"),
316 pIcmpStats
->stats
.icmpInStats
.dwTimestamps
, pIcmpStats
->stats
.icmpOutStats
.dwTimestamps
);
317 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamp Replies"),
318 pIcmpStats
->stats
.icmpInStats
.dwTimestampReps
, pIcmpStats
->stats
.icmpOutStats
.dwTimestampReps
);
319 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Masks"),
320 pIcmpStats
->stats
.icmpInStats
.dwAddrMasks
, pIcmpStats
->stats
.icmpOutStats
.dwAddrMasks
);
321 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Mask Replies"),
322 pIcmpStats
->stats
.icmpInStats
.dwAddrMaskReps
, pIcmpStats
->stats
.icmpOutStats
.dwAddrMaskReps
);
325 DoFormatMessage(dwRetVal
);
327 HeapFree(GetProcessHeap(), 0, pIcmpStats
);
331 VOID
ShowTcpStatistics()
333 PMIB_TCPSTATS pTcpStats
;
336 pTcpStats
= (MIB_TCPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_TCPSTATS
));
338 if ((dwRetVal
= GetTcpStatistics(pTcpStats
)) == NO_ERROR
)
340 _tprintf(_T("\nTCP Statistics for IPv4\n\n"));
341 _tprintf(_T(" %-35s = %lu\n"), _T("Active Opens"), pTcpStats
->dwActiveOpens
);
342 _tprintf(_T(" %-35s = %lu\n"), _T("Passive Opens"), pTcpStats
->dwPassiveOpens
);
343 _tprintf(_T(" %-35s = %lu\n"), _T("Failed Connection Attempts"), pTcpStats
->dwAttemptFails
);
344 _tprintf(_T(" %-35s = %lu\n"), _T("Reset Connections"), pTcpStats
->dwEstabResets
);
345 _tprintf(_T(" %-35s = %lu\n"), _T("Current Connections"), pTcpStats
->dwCurrEstab
);
346 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Recieved"), pTcpStats
->dwInSegs
);
347 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Sent"), pTcpStats
->dwOutSegs
);
348 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Retransmitted"), pTcpStats
->dwRetransSegs
);
351 DoFormatMessage(dwRetVal
);
353 HeapFree(GetProcessHeap(), 0, pTcpStats
);
356 VOID
ShowUdpStatistics()
358 PMIB_UDPSTATS pUdpStats
;
361 pUdpStats
= (MIB_UDPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_UDPSTATS
));
363 if ((dwRetVal
= GetUdpStatistics(pUdpStats
)) == NO_ERROR
)
365 _tprintf(_T("\nUDP Statistics for IPv4\n\n"));
366 _tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Recieved"), pUdpStats
->dwInDatagrams
);
367 _tprintf(_T(" %-21s = %lu\n"), _T("No Ports"), pUdpStats
->dwNoPorts
);
368 _tprintf(_T(" %-21s = %lu\n"), _T("Recieve Errors"), pUdpStats
->dwInErrors
);
369 _tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Sent"), pUdpStats
->dwOutDatagrams
);
372 DoFormatMessage(dwRetVal
);
374 HeapFree(GetProcessHeap(), 0, pUdpStats
);
377 VOID
ShowEthernetStatistics()
379 PMIB_IFTABLE pIfTable
;
383 pIfTable
= (MIB_IFTABLE
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IFTABLE
));
385 if (GetIfTable(pIfTable
, &dwSize
, 0) == ERROR_INSUFFICIENT_BUFFER
)
387 HeapFree(GetProcessHeap(), 0, pIfTable
);
388 pIfTable
= (MIB_IFTABLE
*) HeapAlloc(GetProcessHeap(), 0, dwSize
);
390 if ((dwRetVal
= GetIfTable(pIfTable
, &dwSize
, 0)) == NO_ERROR
)
392 _tprintf(_T("Interface Statistics\n\n"));
393 _tprintf(_T(" Received Sent\n\n"));
394 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Bytes"),
395 pIfTable
->table
[0].dwInOctets
, pIfTable
->table
[0].dwOutOctets
);
396 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Unicast packets"),
397 pIfTable
->table
[0].dwInUcastPkts
, pIfTable
->table
[0].dwOutUcastPkts
);
398 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Non-unicast packets"),
399 pIfTable
->table
[0].dwInNUcastPkts
, pIfTable
->table
[0].dwOutNUcastPkts
);
400 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Discards"),
401 pIfTable
->table
[0].dwInDiscards
, pIfTable
->table
[0].dwOutDiscards
);
402 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Errors"),
403 pIfTable
->table
[0].dwInErrors
, pIfTable
->table
[0].dwOutErrors
);
404 _tprintf(_T("%-20s %14lu\n"), _T("Unknown Protocols"),
405 pIfTable
->table
[0].dwInUnknownProtos
);
408 DoFormatMessage(dwRetVal
);
410 HeapFree(GetProcessHeap(), 0, pIfTable
);
415 PMIB_TCPTABLE tcpTable
;
418 CHAR HostIp
[HOSTNAMELEN
], HostPort
[PORTNAMELEN
];
419 CHAR RemoteIp
[HOSTNAMELEN
], RemotePort
[PORTNAMELEN
];
420 CHAR Host
[ADDRESSLEN
];
421 CHAR Remote
[ADDRESSLEN
];
423 /* Get the table of TCP endpoints */
425 error
= GetTcpTable(NULL
, &dwSize
, TRUE
);
426 if (error
!= ERROR_INSUFFICIENT_BUFFER
)
428 printf("Failed to snapshot TCP endpoints.\n");
429 DoFormatMessage(error
);
432 tcpTable
= (PMIB_TCPTABLE
) HeapAlloc(GetProcessHeap(), 0, dwSize
);
433 error
= GetTcpTable(tcpTable
, &dwSize
, TRUE
);
436 printf("Failed to snapshot TCP endpoints table.\n");
437 DoFormatMessage(error
);
438 HeapFree(GetProcessHeap(), 0, tcpTable
);
442 /* Dump the TCP table */
443 for (i
= 0; i
< tcpTable
->dwNumEntries
; i
++)
445 /* If we aren't showing all connections, only display established, close wait
446 * and time wait. This is the default output for netstat */
447 if (bDoShowAllCons
|| (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_ESTAB
)
448 || (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_CLOSE_WAIT
)
449 || (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_TIME_WAIT
))
451 /* I've split this up so it's easier to follow */
452 GetIpHostName(TRUE
, tcpTable
->table
[i
].dwLocalAddr
, HostIp
, HOSTNAMELEN
);
453 GetPortName(tcpTable
->table
[i
].dwLocalPort
, "tcp", HostPort
, PORTNAMELEN
);
454 GetIpHostName(FALSE
, tcpTable
->table
[i
].dwRemoteAddr
, RemoteIp
, HOSTNAMELEN
);
455 GetPortName(tcpTable
->table
[i
].dwRemotePort
, "tcp", RemotePort
, PORTNAMELEN
);
457 sprintf(Host
, "%s:%s", HostIp
, HostPort
);
458 sprintf(Remote
, "%s:%s", RemoteIp
, RemotePort
);
460 _tprintf(_T(" %-6s %-22s %-22s %s\n"), _T("TCP"),
461 Host
, Remote
, TcpState
[tcpTable
->table
[i
].dwState
]);
464 HeapFree(GetProcessHeap(), 0, tcpTable
);
470 PMIB_UDPTABLE udpTable
;
473 CHAR HostIp
[HOSTNAMELEN
], HostPort
[PORTNAMELEN
];
474 CHAR Host
[ADDRESSLEN
];
476 /* Get the table of UDP endpoints */
478 error
= GetUdpTable(NULL
, &dwSize
, TRUE
);
479 if (error
!= ERROR_INSUFFICIENT_BUFFER
)
481 printf("Failed to snapshot UDP endpoints.\n");
482 DoFormatMessage(error
);
485 udpTable
= (PMIB_UDPTABLE
) HeapAlloc(GetProcessHeap(), 0, dwSize
);
486 error
= GetUdpTable(udpTable
, &dwSize
, TRUE
);
489 printf("Failed to snapshot UDP endpoints table.\n");
490 DoFormatMessage(error
);
491 HeapFree(GetProcessHeap(), 0, udpTable
);
495 /* Dump the UDP table */
496 for (i
= 0; i
< udpTable
->dwNumEntries
; i
++)
499 /* I've split this up so it's easier to follow */
500 GetIpHostName(TRUE
, udpTable
->table
[i
].dwLocalAddr
, HostIp
, HOSTNAMELEN
);
501 GetPortName(udpTable
->table
[i
].dwLocalPort
, "tcp", HostPort
, PORTNAMELEN
);
503 sprintf(Host
, "%s:%s", HostIp
, HostPort
);
505 _tprintf(_T(" %-6s %-22s %-22s\n"), _T("UDP"), Host
, _T("*:*"));
508 HeapFree(GetProcessHeap(), 0, udpTable
);
513 * Translate port numbers into their text equivalent if there is one
516 GetPortName(UINT Port
, PCSTR Proto
, CHAR Name
[], INT NameLen
)
518 struct servent
*pSrvent
;
522 sprintf(Name
, "%d", htons((WORD
)Port
));
525 /* Try to translate to a name */
526 if ((pSrvent
= getservbyport(Port
, Proto
)))
527 strcpy(Name
, pSrvent
->s_name
);
529 sprintf(Name
, "%d", htons((WORD
)Port
));
535 * convert addresses into dotted decimal or hostname
538 GetIpHostName(BOOL Local
, UINT IpAddr
, CHAR Name
[], int NameLen
)
540 // struct hostent *phostent;
543 /* display dotted decimal */
544 nIpAddr
= htonl(IpAddr
);
545 if (bDoShowNumbers
) {
546 sprintf(Name
, "%d.%d.%d.%d",
547 (nIpAddr
>> 24) & 0xFF,
548 (nIpAddr
>> 16) & 0xFF,
549 (nIpAddr
>> 8) & 0xFF,
556 /* try to resolve the name */
559 sprintf(Name
, "%d.%d.%d.%d",
560 (nIpAddr
>> 24) & 0xFF,
561 (nIpAddr
>> 16) & 0xFF,
562 (nIpAddr
>> 8) & 0xFF,
565 if (gethostname(Name
, NameLen
) != 0)
566 DoFormatMessage(WSAGetLastError());
568 } else if (IpAddr
== 0x0100007f) {
570 if (gethostname(Name
, NameLen
) != 0)
571 DoFormatMessage(WSAGetLastError());
573 _tcsncpy(Name
, _T("localhost"), 10);
575 // } else if (phostent = gethostbyaddr((char*)&ipaddr, sizeof(nipaddr), PF_INET)) {
576 // strcpy(name, phostent->h_name);
578 sprintf(Name
, "%d.%d.%d.%d",
579 ((nIpAddr
>> 24) & 0x000000FF),
580 ((nIpAddr
>> 16) & 0x000000FF),
581 ((nIpAddr
>> 8) & 0x000000FF),
582 ((nIpAddr
) & 0x000000FF));
589 _tprintf(_T("\nDisplays current TCP/IP protocol statistics and network connections.\n\n"
590 "NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]\n\n"
591 " -a Displays all connections and listening ports.\n"
592 " -e Displays Ethernet statistics. May be combined with -s\n"
594 " -n Displays address and port numbers in numeric form.\n"
595 " -p proto Shows connections for protocol 'proto' TCP or UDP.\n"
596 " If used with the -s option to display\n"
597 " per-protocol statistics, 'proto' may be TCP, UDP, or IP.\n"
598 " -r Displays the current routing table.\n"
599 " -s Displays per-protocol statistics. By default, Statistics are\n"
600 " shown for IP, ICMP, TCP and UDP;\n"
601 " the -p option may be used to specify a subset of the default.\n"
602 " interval Redisplays selected statistics every 'interval' seconds.\n"
603 " Press CTRL+C to stop redisplaying. By default netstat will\n"
604 " print the current information only once.\n"));
611 * Parse command line parameters and set any options
612 * Run display output, looping over set intervals if a number is given
615 int main(int argc
, char *argv
[])
619 if (WSAStartup(MAKEWORD(2, 2), &wsaData
) != 0)
621 _tprintf(_T("WSAStartup() failed : %d\n"), WSAGetLastError());
625 if (ParseCmdline(argc
, argv
))
634 Sleep(Interval
*1000);