这是我在这里的教程中的代码:
//CONNECT TO REMOTE HOST (CLIENT APPLICATION)
//Include the needed header files.
//Don't forget to link libws2_32.a to your program as well
#include <winsock.h>
SOCKET s; //Socket handle
//CONNECTTOHOST – Connects to a remote host
bool ConnectToHost(int PortNo, char* IPAddress)
{
//Start up Winsock…
WSADATA wsadata;
int error = WSAStartup(0x0202, &wsadata);
//Did something happen?
if (error)
return false;
//Did we get the right Winsock version?
if (wsadata.wVersion != 0x0202)
{
WSACleanup(); //Clean up Winsock
return false;
}
//Fill out the information needed to initialize a socket…
SOCKADDR_IN target; //Socket address information
target.sin_family = AF_INET; // address family Internet
target.sin_port = htons (PortNo); //Port to connect on
target.sin_addr.s_addr = inet_addr (IPAddress); //Target IP
s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); //Create socket
if (s == INVALID_SOCKET)
{
return false; //Couldn't create the socket
}
//Try connecting...
if (connect(s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
{
return false; //Couldn't connect
}
else
return true; //Success
}
//CLOSECONNECTION – shuts down the socket and closes any connection on it
void CloseConnection ()
{
//Close the socket if it exists
if (s)
closesocket(s);
WSACleanup(); //Clean up Winsock
}
我用来编译的命令是:g++ -o winsoc.exe -lwsock32 winsoc.cpp
编译器的输出是:
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0x1b): undefined r
eference to `WSAStartup@8'
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0x3f): undefined r
eference to `WSACleanup@0'
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0x5a): undefined r
eference to `htons@4'
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0x6c): undefined r
eference to `inet_addr@4'
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0x8e): undefined r
eference to `socket@12'
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0xc0): undefined r
eference to `connect@12'
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0xf1): undefined r
eference to `closesocket@4'
C:\Users\Leon\AppData\Local\Temp\ccPq0k1Y.o:winsoc.cpp:(.text+0xf9): undefined r
eference to `WSACleanup@0'
c:/mingw/bin/../lib/gcc/mingw32/4.6.2/../../../libmingw32.a(main.o): In function
`main':
C:\MinGW\msys\1.0\src\mingwrt/../mingw/main.c:73: undefined reference to `WinMai
n@16'
collect2: ld returned 1 exit status
我使用 Windows 7,MinGW 作为我的编译器,并尝试使用 Visual Studio Express 进行编译。