put the asterix and colon the right way round
[reactos.git] / reactos / apps / utils / net / netstat / netstat.c
1 /*
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>
7 */
8 /*
9 * TODO:
10 * sort function return values.
11 * implement -b, -o and -v
12 * clean up GetIpHostName
13 * command line parser needs more work
14 */
15
16 #include <windows.h>
17 #include <winsock.h>
18 #include <tchar.h>
19 #include <stdio.h>
20 #include <iphlpapi.h>
21 #include "netstat.h"
22
23
24 enum ProtoType {IP, TCP, UDP, ICMP} Protocol;
25 DWORD Interval; /* time to pause between printing output */
26
27 /* TCP endpoint states */
28 TCHAR TcpState[][32] = {
29 _T("???"),
30 _T("CLOSED"),
31 _T("LISTENING"),
32 _T("SYN_SENT"),
33 _T("SYN_RCVD"),
34 _T("ESTABLISHED"),
35 _T("FIN_WAIT1"),
36 _T("FIN_WAIT2"),
37 _T("CLOSE_WAIT"),
38 _T("CLOSING"),
39 _T("LAST_ACK"),
40 _T("TIME_WAIT"),
41 _T("DELETE_TCB")
42 };
43
44
45 /*
46 * format message string and display output
47 */
48 DWORD DoFormatMessage(DWORD ErrorCode)
49 {
50 LPVOID lpMsgBuf;
51 DWORD RetVal;
52
53 if ((RetVal = FormatMessage(
54 FORMAT_MESSAGE_ALLOCATE_BUFFER |
55 FORMAT_MESSAGE_FROM_SYSTEM |
56 FORMAT_MESSAGE_IGNORE_INSERTS,
57 NULL,
58 ErrorCode,
59 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
60 (LPTSTR) &lpMsgBuf,
61 0,
62 NULL )))
63 {
64 _tprintf(_T("%s"), (LPTSTR)lpMsgBuf);
65
66 LocalFree(lpMsgBuf);
67 /* return number of TCHAR's stored in output buffer
68 * excluding '\0' - as FormatMessage does*/
69 return RetVal;
70 }
71 else
72 return 0;
73 }
74
75
76 /*
77 *
78 * Parse command line parameters and set any options
79 *
80 */
81 BOOL ParseCmdline(int argc, char* argv[])
82 {
83 INT i;
84
85 TCHAR Proto[5];
86
87 if ((argc == 1) || (_istdigit(*argv[1])))
88 bNoOptions = TRUE;
89
90 /* Parse command line for options we have been given. */
91 for (i = 1; i < argc; i++)
92 {
93 if ( (argc > 1)&&(argv[i][0] == '-') )
94 {
95 TCHAR c;
96
97 while ((c = *++argv[i]) != '\0')
98 {
99 switch (tolower(c))
100 {
101 case 'a' :
102 bDoShowAllCons = TRUE;
103 break;
104 case 'b' :
105 bDoShowProcName = TRUE;
106 break;
107 case 'e' :
108 bDoShowEthStats = TRUE;
109 break;
110 case 'n' :
111 bDoShowNumbers = TRUE;
112 break;
113 case 's' :
114 bDoShowProtoStats = TRUE;
115 break;
116 case 'p' :
117 bDoShowProtoCons = TRUE;
118
119 strncpy(Proto, (++argv)[i], sizeof(Proto));
120 if (!_tcsicmp( "IP", Proto ))
121 Protocol = IP;
122 else if (!_tcsicmp( "ICMP", Proto ))
123 Protocol = ICMP;
124 else if (!_tcsicmp( "TCP", Proto ))
125 Protocol = TCP;
126 else if (!_tcsicmp( "UDP", Proto ))
127 Protocol = UDP;
128 else
129 {
130 Usage();
131 return EXIT_FAILURE;
132 }
133 (--argv)[i]; /* move pointer back down to previous argv */
134 break;
135 case 'r' :
136 bDoShowRouteTable = TRUE;
137 break;
138 case 'v' :
139 _tprintf(_T("got v\n"));
140 bDoDispSeqComp = TRUE;
141 break;
142 default :
143 Usage();
144 return EXIT_FAILURE;
145 }
146 }
147 }
148 else if (_istdigit(*argv[i]))
149 {
150 if (_stscanf(argv[i], "%lu", &Interval) != EOF)
151 bLoopOutput = TRUE;
152 else
153 return EXIT_FAILURE;
154 }
155 // else
156 // {
157 // Usage();
158 // EXIT_FAILURE;
159 // }
160 }
161
162 return EXIT_SUCCESS;
163 }
164
165
166 /*
167 * Simulate Microsofts netstat utility output
168 */
169 BOOL DisplayOutput()
170 {
171 if (bNoOptions)
172 {
173 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
174 ShowTcpTable();
175 return EXIT_SUCCESS;
176 }
177
178 if (bDoShowRouteTable)
179 {
180 /* mingw doesn't have lib for _tsystem */
181 if (system("route print") == -1)
182 {
183 _tprintf(_T("cannot find 'route.exe'\n"));
184 return EXIT_FAILURE;
185 }
186 return EXIT_SUCCESS;
187 }
188
189 if (bDoShowEthStats)
190 {
191 ShowEthernetStatistics();
192 return EXIT_SUCCESS;
193 }
194
195 if (bDoShowProtoCons)
196 {
197 switch (Protocol)
198 {
199 case IP :
200 if (bDoShowProtoStats)
201 {
202 ShowIpStatistics();
203 return EXIT_SUCCESS;
204 }
205 break;
206 case ICMP :
207 if (bDoShowProtoStats)
208 {
209 ShowIcmpStatistics();
210 return EXIT_SUCCESS;
211 }
212 break;
213 case TCP :
214 if (bDoShowProtoStats)
215 ShowTcpStatistics();
216 _tprintf(_T("\nActive Connections\n"));
217 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
218 ShowTcpTable();
219 break;
220 case UDP :
221 if (bDoShowProtoStats)
222 ShowUdpStatistics();
223 _tprintf(_T("\nActive Connections\n"));
224 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
225 ShowUdpTable();
226 break;
227 default :
228 break;
229 }
230 }
231 else if (bDoShowProtoStats)
232 {
233 ShowIpStatistics();
234 ShowIcmpStatistics();
235 ShowTcpStatistics();
236 ShowUdpStatistics();
237 return EXIT_SUCCESS;
238 }
239 else //if (bDoShowAllCons)
240 {
241 _tprintf(_T("\nActive Connections\n"));
242 _tprintf(_T("\n Proto Local Address Foreign Address State\n"));
243 ShowTcpTable();
244 ShowUdpTable();
245 }
246 return EXIT_SUCCESS;
247 }
248
249
250
251
252 VOID ShowIpStatistics()
253 {
254 PMIB_IPSTATS pIpStats;
255 DWORD dwRetVal;
256
257 pIpStats = (MIB_IPSTATS*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPSTATS));
258
259 if ((dwRetVal = GetIpStatistics(pIpStats)) == NO_ERROR)
260 {
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);
279 }
280 else
281 DoFormatMessage(dwRetVal);
282
283 HeapFree(GetProcessHeap(), 0, pIpStats);
284 }
285
286 VOID ShowIcmpStatistics()
287 {
288 PMIB_ICMP pIcmpStats;
289 DWORD dwRetVal;
290
291 pIcmpStats = (MIB_ICMP*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_ICMP));
292
293 if ((dwRetVal = GetIcmpStatistics(pIcmpStats)) == NO_ERROR)
294 {
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);
323 }
324 else
325 DoFormatMessage(dwRetVal);
326
327 HeapFree(GetProcessHeap(), 0, pIcmpStats);
328
329 }
330
331 VOID ShowTcpStatistics()
332 {
333 PMIB_TCPSTATS pTcpStats;
334 DWORD dwRetVal;
335
336 pTcpStats = (MIB_TCPSTATS*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_TCPSTATS));
337
338 if ((dwRetVal = GetTcpStatistics(pTcpStats)) == NO_ERROR)
339 {
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);
349 }
350 else
351 DoFormatMessage(dwRetVal);
352
353 HeapFree(GetProcessHeap(), 0, pTcpStats);
354 }
355
356 VOID ShowUdpStatistics()
357 {
358 PMIB_UDPSTATS pUdpStats;
359 DWORD dwRetVal;
360
361 pUdpStats = (MIB_UDPSTATS*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_UDPSTATS));
362
363 if ((dwRetVal = GetUdpStatistics(pUdpStats)) == NO_ERROR)
364 {
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);
370 }
371 else
372 DoFormatMessage(dwRetVal);
373
374 HeapFree(GetProcessHeap(), 0, pUdpStats);
375 }
376
377 VOID ShowEthernetStatistics()
378 {
379 PMIB_IFTABLE pIfTable;
380 DWORD dwSize = 0;
381 DWORD dwRetVal = 0;
382
383 pIfTable = (MIB_IFTABLE*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IFTABLE));
384
385 if (GetIfTable(pIfTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER)
386 {
387 HeapFree(GetProcessHeap(), 0, pIfTable);
388 pIfTable = (MIB_IFTABLE*) HeapAlloc(GetProcessHeap(), 0, dwSize);
389
390 if ((dwRetVal = GetIfTable(pIfTable, &dwSize, 0)) == NO_ERROR)
391 {
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);
406 }
407 else
408 DoFormatMessage(dwRetVal);
409 }
410 HeapFree(GetProcessHeap(), 0, pIfTable);
411 }
412
413 VOID ShowTcpTable()
414 {
415 PMIB_TCPTABLE tcpTable;
416 DWORD error, dwSize;
417 DWORD i;
418 CHAR HostIp[HOSTNAMELEN], HostPort[PORTNAMELEN];
419 CHAR RemoteIp[HOSTNAMELEN], RemotePort[PORTNAMELEN];
420 CHAR Host[ADDRESSLEN];
421 CHAR Remote[ADDRESSLEN];
422
423 /* Get the table of TCP endpoints */
424 dwSize = 0;
425 error = GetTcpTable(NULL, &dwSize, TRUE);
426 if (error != ERROR_INSUFFICIENT_BUFFER)
427 {
428 printf("Failed to snapshot TCP endpoints.\n");
429 DoFormatMessage(error);
430 exit(EXIT_FAILURE);
431 }
432 tcpTable = (PMIB_TCPTABLE) HeapAlloc(GetProcessHeap(), 0, dwSize);
433 error = GetTcpTable(tcpTable, &dwSize, TRUE );
434 if (error)
435 {
436 printf("Failed to snapshot TCP endpoints table.\n");
437 DoFormatMessage(error);
438 HeapFree(GetProcessHeap(), 0, tcpTable);
439 exit(EXIT_FAILURE);
440 }
441
442 /* Dump the TCP table */
443 for (i = 0; i < tcpTable->dwNumEntries; i++)
444 {
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))
450 {
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);
456
457 sprintf(Host, "%s:%s", HostIp, HostPort);
458 sprintf(Remote, "%s:%s", RemoteIp, RemotePort);
459
460 _tprintf(_T(" %-6s %-22s %-22s %s\n"), _T("TCP"),
461 Host, Remote, TcpState[tcpTable->table[i].dwState]);
462 }
463 }
464 HeapFree(GetProcessHeap(), 0, tcpTable);
465 }
466
467
468 VOID ShowUdpTable()
469 {
470 PMIB_UDPTABLE udpTable;
471 DWORD error, dwSize;
472 DWORD i;
473 CHAR HostIp[HOSTNAMELEN], HostPort[PORTNAMELEN];
474 CHAR Host[ADDRESSLEN];
475
476 /* Get the table of UDP endpoints */
477 dwSize = 0;
478 error = GetUdpTable(NULL, &dwSize, TRUE);
479 if (error != ERROR_INSUFFICIENT_BUFFER)
480 {
481 printf("Failed to snapshot UDP endpoints.\n");
482 DoFormatMessage(error);
483 exit(EXIT_FAILURE);
484 }
485 udpTable = (PMIB_UDPTABLE) HeapAlloc(GetProcessHeap(), 0, dwSize);
486 error = GetUdpTable(udpTable, &dwSize, TRUE);
487 if (error)
488 {
489 printf("Failed to snapshot UDP endpoints table.\n");
490 DoFormatMessage(error);
491 HeapFree(GetProcessHeap(), 0, udpTable);
492 exit(EXIT_FAILURE);
493 }
494
495 /* Dump the UDP table */
496 for (i = 0; i < udpTable->dwNumEntries; i++)
497 {
498
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);
502
503 sprintf(Host, "%s:%s", HostIp, HostPort);
504
505 _tprintf(_T(" %-6s %-22s %-22s\n"), _T("UDP"), Host, _T("*:*"));
506 }
507
508 HeapFree(GetProcessHeap(), 0, udpTable);
509 }
510
511
512 /*
513 * Translate port numbers into their text equivalent if there is one
514 */
515 PCHAR
516 GetPortName(UINT Port, PCSTR Proto, CHAR Name[], INT NameLen)
517 {
518 struct servent *pSrvent;
519
520 if (bDoShowNumbers)
521 {
522 sprintf(Name, "%d", htons((WORD)Port));
523 return Name;
524 }
525 /* Try to translate to a name */
526 if ((pSrvent = getservbyport(Port, Proto)))
527 strcpy(Name, pSrvent->s_name );
528 else
529 sprintf(Name, "%d", htons((WORD)Port));
530 return Name;
531 }
532
533
534 /*
535 * convert addresses into dotted decimal or hostname
536 */
537 PCHAR
538 GetIpHostName(BOOL Local, UINT IpAddr, CHAR Name[], int NameLen)
539 {
540 // struct hostent *phostent;
541 UINT nIpAddr;
542
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,
550 (nIpAddr) & 0xFF);
551 return Name;
552 }
553
554 Name[0] = _T('\0');
555
556 /* try to resolve the name */
557 if (!IpAddr) {
558 if (!Local) {
559 sprintf(Name, "%d.%d.%d.%d",
560 (nIpAddr >> 24) & 0xFF,
561 (nIpAddr >> 16) & 0xFF,
562 (nIpAddr >> 8) & 0xFF,
563 (nIpAddr) & 0xFF);
564 } else {
565 if (gethostname(Name, NameLen) != 0)
566 DoFormatMessage(WSAGetLastError());
567 }
568 } else if (IpAddr == 0x0100007f) {
569 if (Local) {
570 if (gethostname(Name, NameLen) != 0)
571 DoFormatMessage(WSAGetLastError());
572 } else {
573 _tcsncpy(Name, _T("localhost"), 10);
574 }
575 // } else if (phostent = gethostbyaddr((char*)&ipaddr, sizeof(nipaddr), PF_INET)) {
576 // strcpy(name, phostent->h_name);
577 } else {
578 sprintf(Name, "%d.%d.%d.%d",
579 ((nIpAddr >> 24) & 0x000000FF),
580 ((nIpAddr >> 16) & 0x000000FF),
581 ((nIpAddr >> 8) & 0x000000FF),
582 ((nIpAddr) & 0x000000FF));
583 }
584 return Name;
585 }
586
587 VOID Usage()
588 {
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"
593 " option\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"));
605 }
606
607
608
609 /*
610 *
611 * Parse command line parameters and set any options
612 * Run display output, looping over set intervals if a number is given
613 *
614 */
615 int main(int argc, char *argv[])
616 {
617 WSADATA wsaData;
618
619 if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
620 {
621 _tprintf(_T("WSAStartup() failed : %d\n"), WSAGetLastError());
622 return -1;
623 }
624
625 if (ParseCmdline(argc, argv))
626 return -1;
627
628 if (bLoopOutput)
629 {
630 while (1)
631 {
632 if (DisplayOutput())
633 return -1;
634 Sleep(Interval*1000);
635 }
636 }
637
638 if (DisplayOutput())
639 return -1;
640 else
641 return 0;
642 }