Skip to content

Conversation

Copy link

Copilot AI commented Dec 11, 2025

Eliminated 100+ lines of duplicated Winsock initialization, command-line parsing, and error handling code across the NetTool directory.

Changes

Created shared utilities (common_utils.h/cpp):

  • WinsockInitializer - RAII class for automatic Winsock lifecycle management
  • getopt() - BSD-style command-line parsing
  • Error handling functions: err(), errx(), verr(), verrx()

Refactored 6 files to use shared utilities:

  • finger.cpp - Removed ~130 lines (getopt impl, error functions, Winsock boilerplate)
  • whois.cpp, Ping.cpp, nslookup.cpp - Replaced manual Winsock init/cleanup with RAII
  • sock.cpp - Applied RAII to 5 functions

Fixed resource leaks:

  • Added missing closesocket(s6) calls in 4 functions

Example

Before:

WSADATA wsaData;
int err = WSAStartup(MAKEWORD(1, 1), &wsaData);
if (err != 0) {
    fprintf(stderr, "WSAStartup failed\n");
    return;
}
// ... use sockets ...
WSACleanup();

After:

WinsockInitializer winsock(MAKEWORD(1, 1));
if (!winsock.IsInitialized()) {
    fprintf(stderr, "WSAStartup failed\n");
    return;
}
// ... use sockets ...
// Automatic cleanup on scope exit
Original prompt

Find and refactor duplicated code


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI and others added 3 commits December 11, 2025 12:16
…ck initialization

- Created common_utils.h/cpp with shared getopt, error handling, and Winsock RAII wrapper
- Refactored finger.cpp: Removed duplicated getopt, error functions, and WSAStartup/WSACleanup
- Refactored whois.cpp: Use WinsockInitializer RAII wrapper
- Refactored Ping.cpp: Use WinsockInitializer RAII wrapper
- Refactored nslookup.cpp: Use WinsockInitializer RAII wrapper
- Refactored sock.cpp: Use WinsockInitializer RAII wrapper in 5 functions

Co-authored-by: kouzhudong <[email protected]>
Fixed pre-existing bugs where IPv6 sockets (s6) were not being closed in:
- get_all_sock_opt()
- get_tcp_sock_opt()
- get_udp_sock_opt()
- get_sol_sock_opt()

Co-authored-by: kouzhudong <[email protected]>
Updated NetTool.vcxproj to include:
- common_utils.cpp in ClCompile section
- common_utils.h in ClInclude section

This ensures the new shared utility files are built with the project.

Co-authored-by: kouzhudong <[email protected]>
Copilot AI changed the title [WIP] Refactor duplicated code for improved maintainability Refactor duplicated code patterns in NetTool Dec 11, 2025
Copilot AI requested a review from kouzhudong December 11, 2025 12:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants