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
25 enum ProtoType
{IP
, TCP
, UDP
, ICMP
} Protocol
;
26 DWORD Interval
; /* time to pause between printing output */
28 /* TCP endpoint states */
29 TCHAR TcpState
[][32] = {
47 * format message string and display output
49 DWORD
DoFormatMessage(DWORD ErrorCode
)
54 if ((RetVal
= FormatMessage(
55 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
56 FORMAT_MESSAGE_FROM_SYSTEM
|
57 FORMAT_MESSAGE_IGNORE_INSERTS
,
60 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
), /* Default language */
65 _tprintf(_T("%s"), (LPTSTR
)lpMsgBuf
);
68 /* return number of TCHAR's stored in output buffer
69 * excluding '\0' - as FormatMessage does*/
79 * Parse command line parameters and set any options
82 BOOL
ParseCmdline(int argc
, char* argv
[])
88 if ((argc
== 1) || (_istdigit(*argv
[1])))
91 /* Parse command line for options we have been given. */
92 for (i
= 1; i
< argc
; i
++)
94 if ( (argc
> 1)&&(argv
[i
][0] == '-') )
98 while ((c
= *++argv
[i
]) != '\0')
103 bDoShowAllCons
= TRUE
;
106 bDoShowProcName
= TRUE
;
109 bDoShowEthStats
= TRUE
;
112 bDoShowNumbers
= TRUE
;
115 bDoShowProtoStats
= TRUE
;
118 bDoShowProtoCons
= TRUE
;
120 strncpy(Proto
, (++argv
)[i
], sizeof(Proto
));
121 if (!_tcsicmp( "IP", Proto
))
123 else if (!_tcsicmp( "ICMP", Proto
))
125 else if (!_tcsicmp( "TCP", Proto
))
127 else if (!_tcsicmp( "UDP", Proto
))
134 --i
; /* move pointer back down to previous argv */
137 bDoShowRouteTable
= TRUE
;
140 _tprintf(_T("got v\n"));
141 bDoDispSeqComp
= TRUE
;
149 else if (_istdigit(*argv
[i
]))
151 if (_stscanf(argv
[i
], "%lu", &Interval
) != EOF
)
168 * Simulate Microsofts netstat utility output
174 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
179 if (bDoShowRouteTable
)
181 /* mingw doesn't have lib for _tsystem */
182 if (system("route print") == -1)
184 _tprintf(_T("cannot find 'route.exe'\n"));
192 ShowEthernetStatistics();
196 if (bDoShowProtoCons
)
201 if (bDoShowProtoStats
)
208 if (bDoShowProtoStats
)
210 ShowIcmpStatistics();
215 if (bDoShowProtoStats
)
217 _tprintf(_T("\nActive Connections\n"));
218 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
222 if (bDoShowProtoStats
)
224 _tprintf(_T("\nActive Connections\n"));
225 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
232 else if (bDoShowProtoStats
)
235 ShowIcmpStatistics();
240 else //if (bDoShowAllCons)
242 _tprintf(_T("\nActive Connections\n"));
243 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
253 VOID
ShowIpStatistics()
255 PMIB_IPSTATS pIpStats
;
258 pIpStats
= (MIB_IPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPSTATS
));
260 if ((dwRetVal
= GetIpStatistics(pIpStats
)) == NO_ERROR
)
262 _tprintf(_T("\nIPv4 Statistics\n\n"));
263 _tprintf(_T(" %-34s = %lu\n"), _T("Packets Recieved"), pIpStats
->dwInReceives
);
264 _tprintf(_T(" %-34s = %lu\n"), _T("Received Header Errors"), pIpStats
->dwInHdrErrors
);
265 _tprintf(_T(" %-34s = %lu\n"), _T("Received Address Errors"), pIpStats
->dwInAddrErrors
);
266 _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Forwarded"), pIpStats
->dwForwDatagrams
);
267 _tprintf(_T(" %-34s = %lu\n"), _T("Unknown Protocols Recieved"), pIpStats
->dwInUnknownProtos
);
268 _tprintf(_T(" %-34s = %lu\n"), _T("Received Packets Discarded"), pIpStats
->dwInDiscards
);
269 _tprintf(_T(" %-34s = %lu\n"), _T("Recieved Packets Delivered"), pIpStats
->dwInDelivers
);
270 _tprintf(_T(" %-34s = %lu\n"), _T("Output Requests"), pIpStats
->dwOutRequests
);
271 _tprintf(_T(" %-34s = %lu\n"), _T("Routing Discards"), pIpStats
->dwRoutingDiscards
);
272 _tprintf(_T(" %-34s = %lu\n"), _T("Discarded Output Packets"), pIpStats
->dwOutDiscards
);
273 _tprintf(_T(" %-34s = %lu\n"), _T("Output Packets No Route"), pIpStats
->dwOutNoRoutes
);
274 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Required"), pIpStats
->dwReasmReqds
);
275 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Succesful"), pIpStats
->dwReasmOks
);
276 _tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Failures"), pIpStats
->dwReasmFails
);
277 // _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams succesfully fragmented"), NULL); /* FIXME: what is this one? */
278 _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Failing Fragmentation"), pIpStats
->dwFragFails
);
279 _tprintf(_T(" %-34s = %lu\n"), _T("Fragments Created"), pIpStats
->dwFragCreates
);
282 DoFormatMessage(dwRetVal
);
284 HeapFree(GetProcessHeap(), 0, pIpStats
);
287 VOID
ShowIcmpStatistics()
289 PMIB_ICMP pIcmpStats
;
292 pIcmpStats
= (MIB_ICMP
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_ICMP
));
294 if ((dwRetVal
= GetIcmpStatistics(pIcmpStats
)) == NO_ERROR
)
296 _tprintf(_T("\nICMPv4 Statistics\n\n"));
297 _tprintf(_T(" Received Sent\n"));
298 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Messages"),
299 pIcmpStats
->stats
.icmpInStats
.dwMsgs
, pIcmpStats
->stats
.icmpOutStats
.dwMsgs
);
300 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Errors"),
301 pIcmpStats
->stats
.icmpInStats
.dwErrors
, pIcmpStats
->stats
.icmpOutStats
.dwErrors
);
302 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Destination Unreachable"),
303 pIcmpStats
->stats
.icmpInStats
.dwDestUnreachs
, pIcmpStats
->stats
.icmpOutStats
.dwDestUnreachs
);
304 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Time Exceeded"),
305 pIcmpStats
->stats
.icmpInStats
.dwTimeExcds
, pIcmpStats
->stats
.icmpOutStats
.dwTimeExcds
);
306 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Parameter Problems"),
307 pIcmpStats
->stats
.icmpInStats
.dwParmProbs
, pIcmpStats
->stats
.icmpOutStats
.dwParmProbs
);
308 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Source Quenches"),
309 pIcmpStats
->stats
.icmpInStats
.dwSrcQuenchs
, pIcmpStats
->stats
.icmpOutStats
.dwSrcQuenchs
);
310 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Redirects"),
311 pIcmpStats
->stats
.icmpInStats
.dwRedirects
, pIcmpStats
->stats
.icmpOutStats
.dwRedirects
);
312 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echos"),
313 pIcmpStats
->stats
.icmpInStats
.dwEchos
, pIcmpStats
->stats
.icmpOutStats
.dwEchos
);
314 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echo Replies"),
315 pIcmpStats
->stats
.icmpInStats
.dwEchoReps
, pIcmpStats
->stats
.icmpOutStats
.dwEchoReps
);
316 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamps"),
317 pIcmpStats
->stats
.icmpInStats
.dwTimestamps
, pIcmpStats
->stats
.icmpOutStats
.dwTimestamps
);
318 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamp Replies"),
319 pIcmpStats
->stats
.icmpInStats
.dwTimestampReps
, pIcmpStats
->stats
.icmpOutStats
.dwTimestampReps
);
320 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Masks"),
321 pIcmpStats
->stats
.icmpInStats
.dwAddrMasks
, pIcmpStats
->stats
.icmpOutStats
.dwAddrMasks
);
322 _tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Mask Replies"),
323 pIcmpStats
->stats
.icmpInStats
.dwAddrMaskReps
, pIcmpStats
->stats
.icmpOutStats
.dwAddrMaskReps
);
326 DoFormatMessage(dwRetVal
);
328 HeapFree(GetProcessHeap(), 0, pIcmpStats
);
332 VOID
ShowTcpStatistics()
334 PMIB_TCPSTATS pTcpStats
;
337 pTcpStats
= (MIB_TCPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_TCPSTATS
));
339 if ((dwRetVal
= GetTcpStatistics(pTcpStats
)) == NO_ERROR
)
341 _tprintf(_T("\nTCP Statistics for IPv4\n\n"));
342 _tprintf(_T(" %-35s = %lu\n"), _T("Active Opens"), pTcpStats
->dwActiveOpens
);
343 _tprintf(_T(" %-35s = %lu\n"), _T("Passive Opens"), pTcpStats
->dwPassiveOpens
);
344 _tprintf(_T(" %-35s = %lu\n"), _T("Failed Connection Attempts"), pTcpStats
->dwAttemptFails
);
345 _tprintf(_T(" %-35s = %lu\n"), _T("Reset Connections"), pTcpStats
->dwEstabResets
);
346 _tprintf(_T(" %-35s = %lu\n"), _T("Current Connections"), pTcpStats
->dwCurrEstab
);
347 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Recieved"), pTcpStats
->dwInSegs
);
348 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Sent"), pTcpStats
->dwOutSegs
);
349 _tprintf(_T(" %-35s = %lu\n"), _T("Segments Retransmitted"), pTcpStats
->dwRetransSegs
);
352 DoFormatMessage(dwRetVal
);
354 HeapFree(GetProcessHeap(), 0, pTcpStats
);
357 VOID
ShowUdpStatistics()
359 PMIB_UDPSTATS pUdpStats
;
362 pUdpStats
= (MIB_UDPSTATS
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_UDPSTATS
));
364 if ((dwRetVal
= GetUdpStatistics(pUdpStats
)) == NO_ERROR
)
366 _tprintf(_T("\nUDP Statistics for IPv4\n\n"));
367 _tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Recieved"), pUdpStats
->dwInDatagrams
);
368 _tprintf(_T(" %-21s = %lu\n"), _T("No Ports"), pUdpStats
->dwNoPorts
);
369 _tprintf(_T(" %-21s = %lu\n"), _T("Recieve Errors"), pUdpStats
->dwInErrors
);
370 _tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Sent"), pUdpStats
->dwOutDatagrams
);
373 DoFormatMessage(dwRetVal
);
375 HeapFree(GetProcessHeap(), 0, pUdpStats
);
378 VOID
ShowEthernetStatistics()
380 PMIB_IFTABLE pIfTable
;
384 pIfTable
= (MIB_IFTABLE
*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IFTABLE
));
386 if (GetIfTable(pIfTable
, &dwSize
, 0) == ERROR_INSUFFICIENT_BUFFER
)
388 HeapFree(GetProcessHeap(), 0, pIfTable
);
389 pIfTable
= (MIB_IFTABLE
*) HeapAlloc(GetProcessHeap(), 0, dwSize
);
391 if ((dwRetVal
= GetIfTable(pIfTable
, &dwSize
, 0)) == NO_ERROR
)
393 _tprintf(_T("Interface Statistics\n\n"));
394 _tprintf(_T(" Received Sent\n\n"));
395 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Bytes"),
396 pIfTable
->table
[0].dwInOctets
, pIfTable
->table
[0].dwOutOctets
);
397 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Unicast packets"),
398 pIfTable
->table
[0].dwInUcastPkts
, pIfTable
->table
[0].dwOutUcastPkts
);
399 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Non-unicast packets"),
400 pIfTable
->table
[0].dwInNUcastPkts
, pIfTable
->table
[0].dwOutNUcastPkts
);
401 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Discards"),
402 pIfTable
->table
[0].dwInDiscards
, pIfTable
->table
[0].dwOutDiscards
);
403 _tprintf(_T("%-20s %14lu %15lu\n"), _T("Errors"),
404 pIfTable
->table
[0].dwInErrors
, pIfTable
->table
[0].dwOutErrors
);
405 _tprintf(_T("%-20s %14lu\n"), _T("Unknown Protocols"),
406 pIfTable
->table
[0].dwInUnknownProtos
);
409 DoFormatMessage(dwRetVal
);
411 HeapFree(GetProcessHeap(), 0, pIfTable
);
416 PMIB_TCPTABLE tcpTable
;
419 CHAR HostIp
[HOSTNAMELEN
], HostPort
[PORTNAMELEN
];
420 CHAR RemoteIp
[HOSTNAMELEN
], RemotePort
[PORTNAMELEN
];
421 CHAR Host
[ADDRESSLEN
];
422 CHAR Remote
[ADDRESSLEN
];
424 /* Get the table of TCP endpoints */
426 error
= GetTcpTable(NULL
, &dwSize
, TRUE
);
427 if (error
!= ERROR_INSUFFICIENT_BUFFER
)
429 printf("Failed to snapshot TCP endpoints.\n");
430 DoFormatMessage(error
);
433 tcpTable
= (PMIB_TCPTABLE
) HeapAlloc(GetProcessHeap(), 0, dwSize
);
434 error
= GetTcpTable(tcpTable
, &dwSize
, TRUE
);
437 printf("Failed to snapshot TCP endpoints table.\n");
438 DoFormatMessage(error
);
439 HeapFree(GetProcessHeap(), 0, tcpTable
);
443 /* Dump the TCP table */
444 for (i
= 0; i
< tcpTable
->dwNumEntries
; i
++)
446 /* If we aren't showing all connections, only display established, close wait
447 * and time wait. This is the default output for netstat */
448 if (bDoShowAllCons
|| (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_ESTAB
)
449 || (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_CLOSE_WAIT
)
450 || (tcpTable
->table
[i
].dwState
== MIB_TCP_STATE_TIME_WAIT
))
452 /* I've split this up so it's easier to follow */
453 GetIpHostName(TRUE
, tcpTable
->table
[i
].dwLocalAddr
, HostIp
, HOSTNAMELEN
);
454 GetPortName(tcpTable
->table
[i
].dwLocalPort
, "tcp", HostPort
, PORTNAMELEN
);
455 GetIpHostName(FALSE
, tcpTable
->table
[i
].dwRemoteAddr
, RemoteIp
, HOSTNAMELEN
);
456 GetPortName(tcpTable
->table
[i
].dwRemotePort
, "tcp", RemotePort
, PORTNAMELEN
);
458 sprintf(Host
, "%s:%s", HostIp
, HostPort
);
459 sprintf(Remote
, "%s:%s", RemoteIp
, RemotePort
);
461 _tprintf(_T(" %-6s %-22s %-22s %s\n"), _T("TCP"),
462 Host
, Remote
, TcpState
[tcpTable
->table
[i
].dwState
]);
465 HeapFree(GetProcessHeap(), 0, tcpTable
);
471 PMIB_UDPTABLE udpTable
;
474 CHAR HostIp
[HOSTNAMELEN
], HostPort
[PORTNAMELEN
];
475 CHAR Host
[ADDRESSLEN
];
477 /* Get the table of UDP endpoints */
479 error
= GetUdpTable(NULL
, &dwSize
, TRUE
);
480 if (error
!= ERROR_INSUFFICIENT_BUFFER
)
482 printf("Failed to snapshot UDP endpoints.\n");
483 DoFormatMessage(error
);
486 udpTable
= (PMIB_UDPTABLE
) HeapAlloc(GetProcessHeap(), 0, dwSize
);
487 error
= GetUdpTable(udpTable
, &dwSize
, TRUE
);
490 printf("Failed to snapshot UDP endpoints table.\n");
491 DoFormatMessage(error
);
492 HeapFree(GetProcessHeap(), 0, udpTable
);
496 /* Dump the UDP table */
497 for (i
= 0; i
< udpTable
->dwNumEntries
; i
++)
500 /* I've split this up so it's easier to follow */
501 GetIpHostName(TRUE
, udpTable
->table
[i
].dwLocalAddr
, HostIp
, HOSTNAMELEN
);
502 GetPortName(udpTable
->table
[i
].dwLocalPort
, "tcp", HostPort
, PORTNAMELEN
);
504 sprintf(Host
, "%s:%s", HostIp
, HostPort
);
506 _tprintf(_T(" %-6s %-22s %-22s\n"), _T("UDP"), Host
, _T("*:*"));
509 HeapFree(GetProcessHeap(), 0, udpTable
);
514 * Translate port numbers into their text equivalent if there is one
517 GetPortName(UINT Port
, PCSTR Proto
, CHAR Name
[], INT NameLen
)
519 struct servent
*pSrvent
;
523 sprintf(Name
, "%d", htons((WORD
)Port
));
526 /* Try to translate to a name */
527 if ((pSrvent
= getservbyport(Port
, Proto
)))
528 strcpy(Name
, pSrvent
->s_name
);
530 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] [-s] [-p proto] [-r] [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"));
612 * Parse command line parameters and set any options
613 * Run display output, looping over set intervals if a number is given
616 int main(int argc
, char *argv
[])
620 if (WSAStartup(MAKEWORD(2, 2), &wsaData
) != 0)
622 _tprintf(_T("WSAStartup() failed : %d\n"), WSAGetLastError());
626 if (ParseCmdline(argc
, argv
))
635 Sleep(Interval
*1000);