#include "stdio.h" #include "stdint.h" #include "windows.h" #include "ws2tcpip.h" void main(void) { struct sockaddr_in sa; char str[INET_ADDRSTRLEN]; inet_pton(AF_INET, "192.0.2.33", (char *)(&(sa.sin_addr))); inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN); printf("%s\n", str); // prints "192.0.2.33" }
gcc -w inet_pton.c -lws2_32 -o inet_pton D:\zDown\temp\SysTmp\ccH2BQCx.o:inet_pton.c:(.text+0x29): undefined reference to `inet_pton‘ D:\zDown\temp\SysTmp\ccH2BQCx.o:inet_pton.c:(.text+0x50): undefined reference to `inet_ntop‘ collect2.exe: error: ld returned 1 exit status
错误原因:MSYS 默认的 _WIN32_WINNT 是 502 Windows Server 2003
#include "stdio.h" #include "stdint.h" #define _WIN32_WINNT 0x0600 #include "windows.h" #include "ws2tcpip.h" void main(void) { struct sockaddr_in sa; char str[INET_ADDRSTRLEN]; inet_pton(AF_INET, "192.0.2.33", (char *)(&(sa.sin_addr))); inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN); printf("%s\n", str); // prints "192.0.2.33" }
gcc -w inet_pton.c -lws2_32 -o inet_pton
编译成功
分析原因
#define _WIN32_WINNT_NT4 0x0400 // Windows NT 4.0 #define _WIN32_WINNT_WIN2K 0x0500 // Windows 2000 #define _WIN32_WINNT_WINXP 0x0501 // Windows XP #define _WIN32_WINNT_WS03 0x0502 // Windows Server 2003 <--- MSYS 环境默认的版本 #define _WIN32_WINNT_WIN6 0x0600 // Windows Vista #define _WIN32_WINNT_VISTA 0x0600 // Windows Vista #define _WIN32_WINNT_WS08 0x0600 // Windows Server 2008 #define _WIN32_WINNT_LONGHORN 0x0600 // Windows Vista #define _WIN32_WINNT_WIN7 0x0601 // Windows 7 #define _WIN32_WINNT_WIN8 0x0602 // Windows 8 #define _WIN32_WINNT_WINBLUE 0x0603 // Windows 8.1 #define _WIN32_WINNT_WINTHRESHOLD 0x0A00 // Windows 10 #define _WIN32_WINNT_WIN10 0x0A00 // Windows 10 mingw/i686-w64-mingw32/include/ws2tcpip.h #if (_WIN32_WINNT >= 0x0600) ... #define InetNtopA inet_ntop WINSOCK_API_LINKAGE LPCWSTR WSAAPI InetNtopW(INT Family, PVOID pAddr, LPWSTR pStringBuf, size_t StringBufSIze); WINSOCK_API_LINKAGE LPCSTR WSAAPI InetNtopA(INT Family, PVOID pAddr, LPSTR pStringBuf, size_t StringBufSize); #define InetNtop __MINGW_NAME_AW(InetNtop) #define InetPtonA inet_pton WINSOCK_API_LINKAGE INT WSAAPI InetPtonW(INT Family, LPCWSTR pStringBuf, PVOID pAddr); WINSOCK_API_LINKAGE INT WSAAPI InetPtonA(INT Family, LPCSTR pStringBuf, PVOID pAddr); #define InetPton __MINGW_NAME_AW(InetPton) #endif /*(_WIN32_WINNT >= 0x0600)*/